HTML data attributes with jquery

January 13, 2013

I’ve been much happier coding client-side (remember, I am not Client Side Guy) since I’ve discovered the data attribute specifications in HTML5. With these new data attributes you can add custom attributes and values to html tags and still have them be valid!

<div id="myDiv" data-foo="bar" >

This is very nice since you can attach alot of useful data right to a tag that would make sense to hold that data. HTML very much striving to be more like XML in this regard. It’s nice to leave it open-ended with a wildcard so we are able to use whatever terminology after “data-” On top of all this, newer versions of Jquery give you an incredibly easy way to grab that data to pass and use to your needs in javascript.

var getVar = $("#myDiv").data("foo");

The above piece of code finds the data-foo attribute very easily and our alert would respond with the attached value: “bar”.

This has really changed my client side coding and helps make more sense to those that aren’t as comfortable in code to understand. No more dummy elements to pass around values for me!

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive