Wednesday, November 11, 2015

Data attribute in html and setting multiple data-* attributes in JQuery

Have you heard of data attribute in HTML? Well, it's a very handy attribute in developing web applications. We can easily bind custom data to any element in the DOM using the data attribute. This custom data can then be easily fetched using JQuery.

Suppose we have a link like this
<a id="show_data" data-category="Student" data-name="John" data-semester="sixth" href="#" >Show Data</a>
Now we can extract the data in JQuery like this
$("#show_data").click(function() {
         var name = $(this).data("name");
         var category = $(this).data("category");
         var semester = $(this).data("semester");
         alert(name + ", " + category + ", " + semester);
});

Now the reverse, suppose you have a link element or any element and want to set data attribute(not just data, you can set any attribute too) using JQuery
<a href="#" id="our_link">Our link element</a>

$(document).ready(function() {
         $("#our_link).attr({
                      'data-name' : 'John',
                      'data-category' : 'Student',
                      'data-semester' : 'sixth'
         });
});

This way you can set multiple attributes to an element.

No comments: