Categories
JavaScript Answers

How to Get an Element by a Custom Attribute Using JavaScript?

Spread the love

Sometimes, we want to get an element by a custom attribute using JavaScript.

In this article, we’ll look at how to get an element by a custom attribute using JavaScript.

Get an Element by a Custom Attribute Using JavaScript

To get an element by a custom attribute using JavaScript, we can use the document.querySelector method with a select string with the tag and attribute of the element we’re looking for.

For instance, we can write:

<div data-automation="something">
</div>

to add a div.

Then we write:

const div = document.querySelector("div[data-automation='something']")
console.log(div)

to select the div with document.querySelector.

We just put data-automation='something' in the square brackets to select the element with attribute data-automation with value something.

Conclusion

To get an element by a custom attribute using JavaScript, we can use the document.querySelector method with a select string with the tag and attribute of the element we’re looking for.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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