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

  1870 views   2 years ago jQuery

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.

<!DOCTYPE html>
<html lang="en">
<title>jQuery Get the data-id Attribute</title>
    ul li{ 
        display: inline-block;
        margin: 10px;
        list-style: none;
        opacity: 0.8;
    ul li:hover{
        opacity: 1;
<script src=""></script>
    $(".gallery li").on("click", function(){
        var dataId = $(this).attr("data-id");
        alert("The data-id of clicked item is: " + dataId);
    <ul class="gallery">
        <li data-id="1">
            <a href="#">
                <img src="images/club.jpg" alt="Club">
        <li data-id="2">
            <a href="#">
                <img src="images/diamond.jpg" alt="Diamond">
        <li data-id="3">
            <a href="#">
                <img src="images/spade.jpg" alt="Spade">
        <li data-id="4">
            <a href="#">
                <img src="images/heart.jpg" alt="Heart">

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-.

Author : Harsukh Makwana
Harsukh Makwana

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]