Home »
jQuery »
jQuery Examples
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.
Syntax:
$('[data-* = "value"]');
Here, we'll alert the name of the selected element. To get the name for this, we'll use data().
Syntax:
$('[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">
<head>
<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="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<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>
</body>
<script type="text/javascript">
$(document).ready(function(){
$('#button1').on('click',function(){
var name = $('[data-name = "Tom"]').data('name');
alert(name);
});
});
</script>
</html>
Output: