How to select an element by ID using JavaScript

published: 24 Sep 2022

2 min read

How to select an element by ID using JavaScript

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 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 id attribute. However, the value of the id attribute must be unique across the document. In other words, no two elements in 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 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.

Take a look at how to select DOM elements tutorial to learn more about different ways of getting DOM elements in JavaScript.

How to select an element by ID using JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming