getElementById() method. It returns the first element that matches the given ID, or
null if no matching element was found in the document.
The following example shows how you can use the
getElementById() method to select an element from the DOM, and changes its background color to red:
// grab element from DOM const elem = document.getElementById('protip'); // change background color to red elem.style.backgroundColor = 'red';
The above example will update the background color of the element with
id="protip" by using inline styles.
Note: Any HTML element can have an
idattribute. However, the value of the
idattribute must be unique across the document. In other words, no two elements in the same web page can have the same ID.
getElementById() method provides a fast and secure way of selecting a DOM element by its ID. It works in all modern and old browsers including Internet Explorer.
Alternatively, you can also use the
querySelector() method select an HTML element by its ID:
const elem = document.querySelector('#protip');
To select DOM elements by any arbitrary CSS selector like class, tag name or ID, you can use the querySelectorAll() method. It returns all DOM elements that match the given CSS selector.