# How to select a DOM element by ID using JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Mar 6, 2020, updated Oct 15, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-select-dom-elements-by-id

> A short tutorial to learn how to select an HTML element by its ID in vanilla 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:

```javascript
// 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](https://attacomsian.com/blog/javascript-dom-style-property).

> **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:

```javascript
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()`](https://attacomsian.com/blog/javascript-select-dom-elements-by-css-selectors) method. It returns all DOM elements that match the given CSS selector.

Check out [how to select DOM elements](https://attacomsian.com/blog/getting-dom-elements-javascript) tutorial to learn more about different ways of getting DOM elements in JavaScript.
