Custom data in HTML5 tags

Quite often I’d like to add application data to my HTML markup to pass information between server-side scripts generating the HTML markup and client-side jQuery scripts. Prior to HTML5 you could decide to use XHTML and your private namespace; numerous applications (including Facebook and my web sites) use this approach. It works nicely unless you’ve decided to use client-side XSLT transformation in Firefox.

HTML5 gives you another option: embedding custom non-visible data in HTML tags. You can add as many attributes as you wish to a HTML tag as long as they start with the data- prefix. HTML5 compliant browsers will eventually give you DOM access to these attributes through the dataset attribute; in most browsers (ancient IE or Netscape releases might not work) you can get these attributes with the getAttribute (or jQuery attr) call.

You might wonder what the difference is between using non-standard attributes of your choice and standard data- attributes as long as the browsers don’t support the dataset property. If nothing else, your HTML code will be validated by HTML5 validator.

No comments:

Post a Comment