How to Get the data-id Attribute of html Element Using jQuery?

Data-id attribute

you can simply use attr() method to find the data-id attribute of an HTML element.

File Name :

you can get the contents of the attribute data-id you have to use
<a href="" id="7" data-id="786">Get data id attribute </a>
<script>
$(this).attr("data-id") // will return the string "786"
############## OR ################
$(this).data("id") // will return the number 786

</script>
Note :- after data- must be lowercase, e.g. data-idNumber will not work, but data-idnumber will work.

File Name :

<a data-id="786">link</a>
<script>
$(this).data("id") // returns 786
$(this).attr("data-id", "687"); //change the attribute
$(this).data("id") // STILL returns 123!!!
$(this).data("id", "687")
$(this).data("id") // NOW we have 687
</script>

File Name :

<div id="my-div" data-name="mahira" data-nickname="sana">Get Name and nick name</div>
<script>
var myDiv = document.querySelector('#my-div');

myDiv.dataset.name // "mahira"
myDiv.dataset.nickname // "sana"
</script>

File Name :

<select id="selectVehicle">
<option value="1" data-year="2010">Mazda</option>
<option value="2" data-year="2012">Honda</option>
<option value="3" data-year="2006">Mercedes</option>
<option value="4" data-year="2000">Toyota</option>
</select>

<script>
$("#selectVehicle").change(function () {
alert($(this).find(':selected').data("year"));
});
</script>

File Name :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<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="/examples/images/club.jpg" alt="Club">
</a>
</li>
<li data-id="2">
<a href="#">
<img src="/examples/images/diamond.jpg" alt="Diamond">
</a>
</li>
<li data-id="3">
<a href="#">
<img src="/examples/images/spade.jpg" alt="Spade">
</a>
</li>
<li data-id="4">
<a href="#">
<img src="/examples/images/heart.jpg" alt="Heart">
</a>
</li>
</ul>
<p><strong>Note:</strong> Click on any image to get its data-id attribute.</p>
</body>
</html>





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here