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.
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>
var elements = document.querySelectorAll('[data-customerID="hello world"]'); elements.innerHTML = 'it works!';
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