getElementById in JavaScript
getElementById should be used to select unique elements in a HTML document. Selected elements can be manipulated with JavaScript.
Edited: 2021-03-07 12:45
getElementById is used to select an element on a page by its unique ID:
let someElement = document.getElementById("unique_id");
Note. ids must be unique in HTML.
getElementById returns the element that has its id attribute set to the specified name.
You can also use querySelector to select elements by their ID:
let someElement = document.querySelector("#unique_id");
Changing the innerHTML of a selected element
Regardless of the method you use to select the element, you can easily change the innerHtml after having selected the element.
It is best to store the element in a variable, so you do not have to repeatedly select the element; you can operate on the selected element more easily when a variable is used to remember the selection:
someElement.innerHtml = '<p>Hallo World</p>';
If you instead wish to obtain the innerHTML of an element:
let someElement = document.getElementById("unique_id");
let someHTML = someElement.innerHTML;
console.log(someHTML);
// You can also test this with alert() if you find it easier to use
// alert(someHTML);
Changing styles
CSS styles on selected elements can be changed through the style object properties.
The following changes the text color to red:
someElement.style.color = "#ff0000";
You can also use color names:
someElement.style.color = "red";
More properties
- style.background#ffffff | rgb(255, 255, 255) | rgba(0,0,0, 0.5) | url("path-to-image.webp")
- style.border1px solid #000
- style.displaynone | block | flex | inline-block
- style.margin0.5rem | 0.5em | 12px
- style.padding0.5rem | 0.5em | 12px
- style.maxHeight10rem | 10em | 200px
Tell us what you think: