getElementById in JavaScript

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

370 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. Some websites are blocking devtools with malicious JavaScript, so here is how to stop that without disabling JavaScript.
  2. We can not handle HTTP POST data from JavaScript, but we can still access the data while it is in the HTML form.
  3. Should you use querySelector or getElementById?; querySelector is more flexible, and able to perform more complex selections.
  4. the keydown event is not an ideal way to detect text-input by the user; instead you should consider using the input event.

More in: JavaScript Tutorials