How to Get the data-id Attribute
Read this tutorial and learn the right ways of getting the data-id attribute using jQuery two methods. Also, learn more information about the two methods.
jQuery provides multiple methods for manipulating the HTML elements. In this tutorial, you will learn two simple and fast ways of getting data-id.
Assuming you have the following link:
<a data-id="457">link</a>The attr() Method
To get the content of the data-id attribute use the <kbd class="highlighted">attr()</kbd> method, which will return a string:
$(this).attr("data-id"); // returns the string "457"<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
<style>
div p {
display: inline-block;
margin: 10px;
list-style: none;
opacity: 0.8;
}
div p:hover {
opacity: 1;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
</head>
<body>
<div class="divClass">
<p data-id="id1">
<a href="#"> Link1</a>
</p>
<p data-id="id2">
<a href="#"> Link2</a>
</p>
<p data-id="id3">
<a href="#"> Link3</a>
</p>
</div>
<script>
$(document).ready(function() {
$(".divClass p").on("click", function() {
let dataId = $(this).attr("data-id");
alert("The data-id of clicked item is: " + dataId);
});
});
</script>
</body>
</html>The data() Method
In case of jQuery >= 1.4.3 version, you can use the <kbd class="highlighted">data()</kbd> method:
$(this).data("id"); // returns the string "id1"<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
<style>
div p {
display: inline-block;
margin: 10px;
list-style: none;
opacity: 0.8;
}
div p:hover {
opacity: 1;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
</head>
<body>
<div class="divClass">
<p data-id="id1">
<a href="#"> Link1</a>
</p>
<p data-id="id2">
<a href="#"> Link2</a>
</p>
<p data-id="id3">
<a href="#"> Link3</a>
</p>
</div>
<script>
$(document).ready(function() {
$(".divClass p").on("click", function() {
let dataId = $(this).data("id");
alert("The data-id of clicked item is: " + dataId);
});
});
</script>
</body>
</html>tip
jQuery automatically converts
data-*attributes to camelCase when accessed via.data()(e.g.,data-id-numbecomesdataIdNum). The HTML attribute itself can use any valid casing.
The attr() and data() Methods
The <kbd class="highlighted">.data() </kbd> method allows attaching data of any type to DOM elements in a safe way from circular references and memory leaks. The <kbd class="highlighted">data()</kbd> method caches values in memory, so if you update the DOM attribute later using .attr(), .data() will still return the cached value unless you clear it. To set the <kbd class="highlighted">data-*</kbd> attribute value, you can use the attr method. It will get the attribute value for only the first element in the matched set.
Starting with jQuery 1.6, the <kbd class="highlighted">.attr()</kbd> method will return undefined for attributes that have not been set.