How to get data-id attribute value in jQuery

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

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>How to Get data-id and other attribute using jQuery</title>
<title>How to get data-id attribute value in jQuery</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
<script type="text/javascript">
    $(document).ready(function() {
        $(".getId").click(function(){            
            var id = $(this).attr("data-id");
            alert("The data-id of clicked item is: " + id);
        });
    });
</script> 
</head>
<body>
   <table border="1" cellpadding="20px;">
<tbody>
    <tr>
        <td>1</td>
        <td>1001</td>
        <td>Raj</td>
        <td>MCA</td>
        <td><button class="getId" data-id="1001">Click Data ID</button> </td>
    </tr><tr>
        <td>2</td>
        <td>1001</td>
        <td>Dinesh</td>
        <td>BCA </td>
        <td><button class="getId" data-id="1001">Click Data ID</button> </td>
    </tr><tr>
        <td>3</td>
        <td>1003</td>
        <td>Umesh</td>
        <td>DCA</td>
        <td><button class="getId" data-id="1003">Click Data ID</button></td>
    </tr>
</tbody>   
</table>
</body>
</html>   

You can also use the jQuery data() method (jQuery version >= 1.4.3), to get the data-attribute of an element.

Syntax like


 $(document).ready(function() {
        $(".getId").click(function(){            
            var id = $(this).data("id");
            alert("The data-id of clicked item is: " + id);
        });
    });
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments