Skip to content
the poor coder

how to select data attribute in javascript

Poor Man
Published
Reading time
1 min read
On this page

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.

Text

// 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.

Text

// 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.

Text

// 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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC