jQuery

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

In this tutorial, we are going to see how to get the data-id attribute of an element in jQuery. You can use the method data() of jQuery (jQuery version> = 1.4.3) to get the data attribute of an element using the following syntax: $(element).data(key).

To get the id using the method data(), you can use the statement such as $(this).data("id"). The key is the rest of the game after removing data-.
 

 

HTML Code:
<a href="#" data-id="stackhowto">This is a link</a>

 

jQuery Code:
(function() {
    var id = $("a").data("id");
    console.log(id);  
})()

Output:

stackhowto
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *