In JavaScript, you can almost select any element from the DOM based on its unique ID by using the getElementById()
method. It returns the first element that matches the given ID or null
if no matching DOM 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"
using inline styles.
Note: Any HTML element can have an
id
attribute. However, the value of theid
attribute must be unique across the document. In other words, no two elements on the same web page can have the same ID.
The 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 to 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.
Check out how to select DOM elements tutorial to learn more about different ways of getting DOM elements in JavaScript.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.