Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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.

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Check If Object is an Array in JavaScript... >>
<< How to Detect a Mobile Device in jQuery...