attr()
MethodYou 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.
<!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-1.12.4.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-
.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Laravel 8 API authentication using Passport from the scratch
Laravel provides 2 ways API authenticati...Angular 9 - CRUD Example with PHP and MySql
In this tutorial, you'll learn to en...How to Preview an Image Before it is Uploaded Using jQuery
Use the JS readAsDataURL() Method You...PHP Count Number of Pages in PDF File
In this post, I will give you a simple e...Create Fake Data using Faker and Factory in Laravel 8
In the process of building application,...