Html5 and data- * attributes?

With all due respect to the Html5 data attribute

When I have a code like this:

<li class="user" data-name="Royi Namir" data-city="Boston" data-lang="js" data-food="Bacon"> </li> 

I add quite a lot of redundant characters to the document.

I only need this type of data-XXX to do:

myDomElement.dataset[xxx];

However i could easily do that

 <li class="user" dn="Royi Namir" dc="Boston" dl="js" df="Bacon"> </li> 

Without these additional data- prefixes (and save a lot of extra characters). and read it using the “start with” selector of type [d ^] - jQuery API

Did I miss something?

+6
source share
3 answers

You can use this:

 <li class="user" data-user='{"name":"Royi Namir", "city":"Boston", "lang":"js", "food":"Bacon"}'> </li> 

And then

 var user = JSON.parse(element.dataset.user); 

Using jQuery, it is even simpler:

 var user = $(element).data('user'); 

And if you want to get all your users:

 var ​users = $('[data-user]').map(function(){return $(this).data('user')}); 

There will be less redunduncy and a directly used structure, especially with deeper properties. Data attributes are not just for rows.

But the main thing in data- attributes is the normalization of practice. Now it’s clear that when viewing HTML, which attributes are the standard HTML (view) attributes and which attributes are data (specific to your application logic).

+14
source

An alternative that I sometimes use is to format the string data- *, for example, querystring, for example.

 <li class="user" data-cn="dn=Royi Namir&dc=Boston&dl=js&df=Bacon"> 

And convert this to an object using:

 function getData(id,el){ var data = el.getAttribute('data-'+id).split('&'), ret = {}; data.map( function(a){ var curr = a.split('='); this[curr[0]] = curr[1]; return a; }, ret ); return ret; } 

This is less error prone (do not worry about apostrophes, etc.) and is better read in my opinion.

jsFiddle

+2
source

If you add quite a lot of redundant characters, you might want to reorganize your application in a client-side MVC style — basically transferring data as JSON and process it using templates.

data-* attributes are cool, and they allow you to input material into the DOM, while keeping your document standard, but if you rely on using the DOM itself as the data level of your application, I highly recommend that you go with the above solution.

+1
source

All Articles