Different ways to get element by id in javascript

Following are the different possible ways through which we can get the DOM element by id in javascript.

Id’s are used to represent unique HTML elements.

All the elements inside the DOM can be accessed using only document object.

Using getElementById()

getElementById() method takes the name of the id and returns the first matching element. Otherwise null is returned.

<div id="prashant">Hello World!</div>

<script>
let element = document.getElementById('prashant');
console.log(element);
</script>

//<div id="prashant">Hello World!</div>

getElementById() is the method of the document object which is used to get the element by the given case sensitive id.


Using querySelector()

We can use querySelector() as an alternative to get element by id in javascript. It uses CSS selectors to select the elements and returns the first matching element. If no matching element is found then it returns null.

<div id="prashant">Hello World!</div>

<script>
let element = document.querySelector('#prashant');
console.log(element);
</script>

//<div id="prashant">Hello World!</div>

Using attribute selector to get element by id

We can also use attribute selector [id="prashant"] to get the element by id.

<div id="prashant">Hello World!</div>

<script>
let element = document.querySelector('[id="prashant"]');
console.log(element);
</script>

//<div id="prashant">Hello World!</div>

Apart from all these we can also use querySelectorAll(), But it is used to select list of matching elements. As each element has unique id we can skip this selector.

Leave a Reply

Your email address will not be published. Required fields are marked *