15

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

 2 years ago
source link: https://www.laravelcode.com/post/how-to-get-the-data-id-attribute-of-an-element-using-jquery
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Ad byValueimpression

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK