select element by data attribute

How to Select Element by Data Attribute in jQuery

Often web developers use data attributes to store information in DOM elements of web pages. So you may also need to retrieve this information from time to time. It can be confusing to select element by data attribute in jQuery, since DOM elements are generally selected using ID, class or name attributes. In this article, we will learn how to select element by data attribute in jQuery.


How to Select Element by Data Attribute in jQuery

Let us say you have the following DOM element.

<div id='MyDiv' class='myClass' data-test='hello world'>Hello World</div>

You can easily select the above div by its data attribute using the following command.

$("[data-test='hello world']") 

The above selector will select all elements on your page with attribute data-test=’hello world’.

But there are some nuances you need to keep in mind while working with data attributes. If you use only $(‘[data-test]’), without specifying its value, then jQuery will select all elements with the presence of data-test attribute, whether it has any value assigned or not. For example, this selector will select both the following elements.

<div data-test='hello world'>hello world</div>
<div data-test>hello world</div>

That is why it is important to specify the value of data attribute using = operator, as we have done initially. It performs an exact match for attribute value and selects only the matching element.

Also, if you use ~= instead of only = it will select all elements that contain specified attribute value, even if there is no exact match. For example, if you use $(“[data-test~=‘hello world’]”) instead of $(“[data-test=‘hello world’]”) then it will match both the following elements.

<div data-test="hello world">Exact Matches</div>
<div data-test="this has hello world in it">Attribute contains value</div>

Alternatively, you can also use a plain JavaScript solution if you don’t wish to use jQuery. The selector expression remains the same as above, but we use document.querySelectorAll() function instead of $().

var elements = document.querySelectorAll('[data-customerID="hello world"]');

elements[0].innerHTML = 'it works!';

In this article, we have learnt how to select element by data attribute in jQuery as well as JavaScript. Please note, if there is only one element that matches your selector it will return a single element. But if there are multiple elements that match your selector expression then it will return an array of elements. So you will need to address the result of above functions accordingly.

Also read:

How to Truncate All Tables of Database in MySQL
How to Get Primary Key of Newly Inserted Row in PostgreSQL
How to Get Primary Key of Newly Inserted Row in MySQL
How to Find Tables With Column Names in MySQL
How to Find my.cnf Location in MySQL

Leave a Reply

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