Select Elements by Attribute Name using JavaScript


Borislav Hadzhiev

Last updated: Dec 27, 2021


Photo from Unsplash

Select Elements by Attribute Name using JavaScript #

To select elements by an attribute name, pass a selector with the attribute's name to the querySelectorAll() method, e.g. document.querySelectorAll('[title]'). The querySelectorAll method will return a collection of the elements that have the provided attribute set.

Here is the html for the examples in the article.

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

And here is the related JavaScript code.

// ✅ All elements with `title` attribute const elements = document.querySelectorAll('[title]'); console.log(elements); // 👉️ [div, div] // ✅ First element with `title` attribute const element = document.querySelector('[title]'); console.log(element); // 👉️ div

The first example uses the document.querySelectorAll() method to get a collection of all elements that have the title attribute set.

The second example uses the document.querySelector() method to get the first element in the document that has the title attribute set.

In short, if you need a collection of elements, use the document.querySelectorAll method, and if you need the first element that matches the provided selector, use the document.querySelector method.

You can also narrow things down by selecting only div elements by a specific attribute name.
// ✅ Get `div` elements with `title` attribute const elements = document.querySelectorAll('div[title]'); console.log(elements); // 👉️ [div, div]

The code snippet targets only div elements that have the title attribute set.

Any span or p elements that have the attribute set would not match the query.

An alternative approach is to select the elements from the DOM and iterate over the NodeList checking if each element has the specific attribute set.

const elements = document.getElementsByTagName('*'); const matches = []; for (const element of elements) { if (element.hasAttribute('title')) { matches.push(element); } } console.log(matches); // 👉️ [div, div]

We used the getElementsByTagName method to select all elements in the DOM.

You could narrow this down to only div or p elements to work with a smaller collection.

The next step is to use the for...of loop to iterate over the NodeList.

On each iteration, we check if the element has the title attribute set and if it does, we push the element to the matches array.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.