Selecting element by data attribute with jQuery

In this jQuery tutorial, let's understand how can we select an element by using data attribute with the help of jQuery?
Submitted by Pratishtha Saxena, on August 24, 2022

First and foremost, let's understand what is data attribute? When we declare normal attributes of an element like id, name, value, etc. those attributes are stored on the element itself. But when a data attribute is declared for an element, then data for those attributes are stored on the webpage or the browser. This storage location can be some sort of internal storage that you can refer to. Also, if we make any changes in the values over here, it will not reflect in the inspection section of the webpage.

Data Attributes are declared as:

data-type = "..."
data-name = "..."
data-age = "..."
data-number = "..."

This way many numbers of data attributes can be declared. The only thing to keep in mind is that the data attribute needs to be started with the data-*

Now, since we are all clear with the basis of data attributes, let's move on to the concept of selecting an element using these data attributes with jQuery.

There is a very straightforward way of doing this. Specify the data attribute (data-*) and its value that needs to be used for the selection of the element.


$('[data-* = "value"]');

Here, we'll alert the name of the selected element. To get the name for this, we'll use data().


$('[data-* = "value"]').data('value');

All of the above will get cleared when this will be discussed in an example.

Example to select element by data attribute with jQuery

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src=""></script>
    <h2 data-name="John">Select Elements By Data Attributes</h2>
    <div id="myDiv" data-name="Tom" data-age="20">Welcome to Include Help !!</div>
    <p data-name="Harry">jQuery Tutorial</p>
    <button type="button" id="button1">Click Here</button>
  <script type="text/javascript">
            var name = $('[data-name = "Tom"]').data('name');


Example: Selecting element by data attribute with jQuery

All jQuery Examples

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.