how to select data attribute in javascript

How to Select Data Attribute in JavaScript

You might have come across situations where you need to select an element based on its data attribute. In JavaScript, it is very easy to select elements with data attributes. Here are some ways to do that.

Using the querySelector() Method

The querySelector() method is used to select the first element that matches a specified CSS selector. You can use this method to select elements based on data attributes as well.


// Select the element with data-id attribute equal to 123
const element = document.querySelector('[data-id="123"]');

The above code selects the first element with a data-id attribute equal to 123.

Using the querySelectorAll() Method

The querySelectorAll() method is similar to the querySelector() method, but it returns all elements that match a specified CSS selector. You can use this method to select multiple elements based on data attributes.


// Select all elements with data-type attribute equal to "button"
const elements = document.querySelectorAll('[data-type="button"]');

The above code selects all elements with a data-type attribute equal to "button".

Using the dataset Property

The dataset property is used to access custom data attributes on an element. You can use this property to get or set the value of a data attribute.


// Get the value of data-id attribute
const id = element.dataset.id;

// Set the value of data-type attribute
element.dataset.type = "button";

The above code gets the value of a data-id attribute and sets the value of a data-type attribute.

These are some ways to select elements based on data attributes in JavaScript. You can use any of these methods based on your requirements.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe