Storing data in HTML tags as custom attributes

7.2k views Asked by At

Is it a good practice storing related information in the HTML tag?

$("#my_div").append("<span id='info' boo='foo'/>");
$("#info").attr("boo");

I've encountered with such technique (and slightly borrowed it) in TAL (in ZPT) where you could use tal:attributes statement to modify HTML tags (e.g. passing the value of boo variable from backend to be rendered in the final document as attribute value):

<span id='info' tal:attributes='boo view/boo'>

result:

<span id='info' boo='foo'>

Will this technique break a document someday, or it is safe by the spec?

2

There are 2 answers

1
Keith Norman On BEST ANSWER

The right way to do it is to use data-* attributes:

http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#embedding-custom-non-visible-data-with-the-data-attributes

Tangentially, jQuery has a special method for working with these as well. For example:

<p id='string' data-user_name='thedude'></p>
$('#string').data('user_name') => "thedude"
typeof $('#string').data('name') => "string"

<p id='number' data-user_id='12345'</p>
typeof $('#number').data('user_id') => "number"

<p id='boolean' data-user_is_active='true'></p>
typeof $('#boolean').data('user_is_active') => "boolean"

<p id = 'json' data-user='{"name": "the dude", "id": "12345"}'></p>
typeof $('#json').data('user') => "object"
// embedding JSON is extremely useful in my experience
1
Lan On

w3.org allows in HTML5 to use user custom data in html tags;

See the section:

3.2.3.9 Embedding custom non-visible data with the data-* attributes

A custom data attribute is an attribute in no namespace whose name starts with the string "data-", has at least one character after the hyphen [...]

Example:

<ol>
 <li data-length="2m11s">Beyond The Sea</li>
 ...
</ol>

So, I'll say that it is a accepted practice for HTML5.