I am following the “best practices” concerning the DOM manipulation topic. I am having a problem though. Before, my code was:
for(var i=0;i<size;++i){
var $li = $('<li/>',{some propertie..}).data(some values);
$ul.append($li);
}
After reading a bit of performance tips, I concluded that I need to replace this into:
var str_html = '';
for(var i=0;i<size;++i){
var li = '<li ...>...</li>';
str_html += li;
}
$ul.append(str_html);
My question is, how can I add the data parameters in this second approach, the same way I was doing in the first one (for each li element)?
Thanks!
Since jQuery
1.4.3you can setdata attributeshave a read. This would look like:jQuery will automatically pull all
data-attributes into the elements data-expando. So you could access the above example with:You actually can put in any type of data into such an attribute, even
JSON decodedobject-string literals (which automatically get parsed by jQuery):is translated into