What is data attribute and how to use it?
The data-* attribute allow developers to add some extra information to an element on a web page (or an application), which can later be used for processing.
👉 Any element whose attribute has a prefix (or starts with) a data- (the word data, followed by a hyphen), is a data attribute. For example, I have a <div> element and I want to attach some basic information with it, using "data attribute".
<div class="emp" data-name="arun" data-empcode="cd001"> some text here... </div>
I have two data attributes assigned to the <div> element, namely, "data-name" and "data-empcode". Each attribute has some value. Similarly, you can have multiple <div> elements, each having some unique data.
There are many ways you can extract the values associated with these (and many) data attributes. For example,
<div class="emp" data-name="arun" data-empcode="cd001"> some text here... </div> <script> let emp = document.getElementsByClassName("emp"); let empName = emp[0].getAttribute("data-name"); let empCode = emp[0].getAttribute("data-empcode"); alert(empName + ' ' + empCode); </html>
👉 How to get all elements inside a DIV with specific text as ID using plain JavaScript
Find Elements by its data Attribute value using jQuery
Now, let’s see how using a simple jQuery method we can find all elements by its data attributes.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <style> .activeBirds::after { color: red; content: "*"; } </style> </head> <body> <h2>Click the button to find which bird in the list is of type "sparrow".</h2> <div> <div class="birds" data-bird-type="dove"> Mourning Dove </div> <div class="birds" data-bird-type="sparrow"> Abert's Towhee </div> <div class="birds" data-bird-type="sparrow"> Cassin's Sparrow </div> <div class="birds" data-bird-type="hawk"> Cooper's Hawk </div> <div class="birds" data-bird-type="hawk"> Black Vulture </div> <div class="birds" data-bird-type="sparrow"> Canyon Towhee </div> </div> <p> <input type="button" id="bt" value="Click it!" /> </p> </body> <script> $(document).ready(function () { $('#bt').click(function () { // Change the value "sparrow" with "hawk" to find the hawks in the list. $('.birds[data-bird-type="sparrow"]').addClass('activeBirds'); }); }); </script> </html>
I have few <div> elements and each has a single data attribute named data-bird-type. The elements have a common class named birds. Different birds come under different category.
I want to find a specific type of bird (lets say the sparrow and there are many birds in this type) and change the class of every elements of type sparrow.
Inside the script, I am using the jQuery Attribute Equals Selector to search for elements with a specific attribute (in our case data-bird-type) and a specific value (in our case sparrow).
$('.birds[data-bird-type="sparrow"]')