How to use data attribute of html5 in JavaScript, jQuery, CSS3

In HTML5 we can also define our own attributes. Normally those attributes are prefixed with data-*. However it is not compulsory but if you are not using data prefix then may not work in all browsers.
Those attributes are very helpful because we can easily access those attributes with JavaScript, jQuery, and CSS. Even we can store entire JSON data in those data attributes.

In HTML5

<section
	id="posts"
	data-next="102"
	data-author-name="It's Me"
>
	...
</section>

In JavaScript
For accessing data attribute in JavaScript we can use DOM structure with dataset object. we need to write the part of the attribute name after data- (note that dashes are converted to camelCase).

Note: Internet Explorer does not support the dataset but you’d need to read them out with getAttribute() instead.

var section = document.getElementById('posts');
var next = section.dataset.next 		// "102"
var name = section.dataset.authorName 	// "It's Me"

In jQuery
For accessing data attribute in jQuery we can simply use data() method of jQuery. This method can be used for retrieve value an well as set value.

var next = $( "#posts" ).data("next");
$( "#posts" ).data("next", 103);

In CSS3
Even we can use those data attributes in CSS, which helps us to provide style based on the value stored in data attribute. It’s simple as normal accessing normal attributes. In this example i am change font color of post whose next is 110.

section[data-next='110'] {
	color: red;
}

Leave a Reply

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