How to select a DOM 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 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 = '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 the id 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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.