getElementById in JavaScript

getElementById should be used to select unique elements in a HTML document. Selected elements can be manipulated with JavaScript.

122 views

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";
The elephant danced with the little mouse until it was completely exhausted.

More properties

  • style.background
    #ffffff | rgb(255, 255, 255) | rgba(0,0,0, 0.5) | url("path-to-image.webp")
  • style.border
    1px solid #000
  • style.display
    none | block | flex | inline-block
  • style.margin
    0.5rem | 0.5em | 12px
  • style.padding
    0.5rem | 0.5em | 12px
  • style.maxHeight
    10rem | 10em | 200px

Tell us what you think:

  1. Should you use querySelector or getElementById?; querySelector is more flexible, and able to perform more complex selections.
  2. the keydown event is not an ideal way to detect text-input by the user; instead you should consider using the input event.
  3. Easily check if an element is either hovered or in focus using plain JavaScript.
  4. The Width and Height of the browser Window can be obtained through the innerWidth and innerHeight properties; these can be checked by an event handler to detect resize events.

More in: JavaScript Tutorials