Get the First element with specific Class name using JS

avatar

Borislav Hadzhiev

Mon Jan 10 20222 min read

Get the First element with specific Class name using JS #

Use the querySelector() method to get the first element with a specific class name, e.g. document.querySelector('.box'). The method returns the first element that matches the provided selector or null if no element matches.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const first = document.querySelector('.box'); console.log(first); // 👉️ div.box console.log(first.textContent); // 👉️ "Box 1"

The document.querySelector method takes a string that is a valid CSS selector as a parameter.

The method returns the first element in the document that matches the provided selector or null if no element matches.

Alternatively, you could use the getElementsByClassName method to get an HTMLCollection of the matching elements and access the element at index 0 to get the first element with a specific class.

index.js
const first = document.getElementsByClassName('box')[0]; console.log(first); // 👉️ div.box

Notice that the getElementsByClassName method takes the class name and not a selector as a parameter.

If no elements with the provided class name exist in the DOM, an empty HTMLCollection is returned.

If you are unable to find the element you are looking for, you can use the getElementsByClassName method to get a collection of all elements with the specific class name and iterate over the collection looking for the element.

index.js
const boxes = document.getElementsByClassName('box'); let element; for (const box of boxes) { if (box.textContent.toLowerCase() === 'box 1') { console.log('✅ box found'); element = box; break; } } console.log(element); // 👉️ div.box console.log(element.textContent); // 👉️ "Box 1"

We used the for...of loop to iterate over the collection of elements with the class box.

On each iteration, we check if the element has a text content of box 1, and if the condition is met, we assign the element to a variable.

When the element is found, use the break keyword to break out of the for loop and avoid doing unnecessary work.

Use the search field on my Home Page to filter through my more than 1,000 articles.