How to Get the data-id Attribute of an Element Using jQuery
Topic: JavaScript / jQueryPrev|Next
Answer: Use the jQuery attr()
Method
You can simply use the jQuery attr()
method to find the data-id
attribute of an HTML element.
The following example will show you how to get the data-id of the clicked item.
Example
Try this code »<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Get the data-id Attribute</title>
<style>
ul li{
display: inline-block;
margin: 10px;
list-style: none;
opacity: 0.8;
}
ul li:hover{
opacity: 1;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$(".gallery li").on("click", function(){
var dataId = $(this).attr("data-id");
alert("The data-id of clicked item is: " + dataId);
});
});
</script>
</head>
<body>
<ul class="gallery">
<li data-id="1">
<a href="#">
<img src="images/club.jpg" alt="Club">
</a>
</li>
<li data-id="2">
<a href="#">
<img src="images/diamond.jpg" alt="Diamond">
</a>
</li>
<li data-id="3">
<a href="#">
<img src="images/spade.jpg" alt="Spade">
</a>
</li>
<li data-id="4">
<a href="#">
<img src="images/heart.jpg" alt="Heart">
</a>
</li>
</ul>
</body>
</html>
Alternatively, you can also use the jQuery data()
method (jQuery version >= 1.4.3), to get the data-attribute of an element using the syntax like $(element).data(key)
.
That means in the above example to get the data-id
using data()
method you can use the statement like $(this).data("id")
. Key is the rest of the part after removing data-
.
Related FAQ
Here are some more FAQ related to this topic: