XHTML Alternative to HTML5 Data Attributes
Introduction
I tend to write my own cross browser UI components and always strive to reduce the number of elements rendered in a page whilst also ensuring the mark-up validates. In situations where I need a key value pair but do not want to insert hidden fields, I use a custom CSS selector such as
<div id="mydiv" class="data-usedialogs-true">
prefix-key-value
I then have a script that executes when the page loads and goes through all (or selected) elements extracting the key value pairs and binding them to the actual element within the DOM.
This allows me to read/test the value using JavaScript without any manual parsing:
if (document.getElementById("mydiv").prefix.property=="true")
{
// do something...
}
This method is my w3c compliant alternative to the new HTML5 data attribute, whereby you can add custom data attributes to elements e.g.
<div id="mydiv" data-usedialogs="true">.
The good thing about this method is you can change the attribute, so you could have
<div id="mydiv" class="settings-autohide-true">
resulting in:
if (document.getElementById("mydiv ").settings.autohide=="true")
{
// do something...
}
How does the script work?
When the script executes it looks through the DOM for all elements with a class name matching the regular expression prefix-[A-Za-z0-9]{1,}- [A-Za-z0-9]{1,}. Once it finds an element, it then creates a custom attribute on that element and assigns an array containing the keys and values found within the matching selector(s).
This means you can have multiple key value pairs within the same element
<div id="mydiv" class="data-usedialogs-true data-autohide-true">
Allowing you to read the values back in JavaScript as:
if (element.data.usedialogs=="true")
{
// do something...
}
and
if (element.data.autohide=="true")
{
// do something...
}
The Script
//
// turns custom class names into key/value expando properties
//
// css class data-title-hello can be retrieved using element.data.title
//
function bindCssData(t /*tagName*/, p /*prefix*/)
{
p = p || "data";
t = t || "*";
var els = document.getElementsByTagName(t);
var reg = new RegExp("^(" + p + ")-([A-Z0-9]{1,})-([A-Z0-9]{1,})$", "i");
for (var i=0, l=els.length; i<l; i++)
{
var cssNames = (els[i].className != "") ? new String(els[i].className).split(' ') : [];
if (cssNames.length<=0) continue;
for (var ii=0, ll=cssNames.length; ii<ll; ii++)
{
var m = reg.exec(cssNames[ii]);
if (m && m.length >= 2) {
els[i][p] = els[i][p] || new Array();
els[i][p][m[2]] = m[3];
}
}
}
}
To use the script call bindCssData() from within your window.onload function. If you do not pass any parameters to the function, it will parse all elements looking for a prefix of data. To make this faster, consider calling the function with only the element types (tagName) you want to affect:
bindCssData("span");
or
bindCssData("span", "settings");
Anticipated Backlash -> Auto Response
Of course, there will be many designers/developers out there that will disagree with the concept of using CSS selectors to carry data to client side scripts. However, in my defence and with progressive enhancement in mind, this is the cleanest solution I could come up with without inserting unnecessary bloat into the page. In addition, the ability to define your own prefix reduces the potential of a conflict with actual page styles.
For example, you could an unnatural CSS selector such as __cssdata-key-value.
Feedback
I am always stupidly busy and don't get much time to knock-up these articles so they might be areas lacking explanation. If you feel I need to expand/correct anything please leave a comment and I will update it as soon as I can.
Post Comment
xCDoj5 Wow! Thank you! I always needed to write on my blog something like that. Can I take a fragment of your post to my site?
cyx3qG It is truly a great and useful piece of info. I am glad that you shared this helpful information with us. Please keep us informed like this. Thank you for sharing.
Pretty section of content. I just stumbled upon your web site and in accession capital to assert that I get actually enjoyed account your blog posts. Any way I will be subscribing to your feeds and even I achievement you access consistently rapidly.| а
dBnpg8 I was suggested this blog by my cousin. I am not sure whether this post is written by him as no one else know such detailed about my trouble. You are wonderful! Thanks!
AJlHK8 you may have a terrific blog here! would you like to make some invite posts on my blog?
"hi, this is the first time i visit here, your blog is very interesting. i really like it."
"It appears that you�ve put a good amount of effort into your article and I demand a lot more of these on the web these days. I sincerely got a kick out of your post. I do not have a bunch to say in reply, I only wanted to register to say, good work!"
"I cherished reading this article I will be sure to tell my close friends about this and hyperlink to it too. Thanks"
"hey there I just wanted to comment your blog and say that I really enjoyed reading your blog post here. It was very informative and I also digg the way you write! Keep it up and I�ll be back to read more soon mate"
"It appears that you�ve put a good amount of effort into your article and I demand a lot more of these on the web these days. I sincerely got a kick out of your post. I do not have a bunch to say in reply, I only wanted to register to say, good work!"
"Took me time to learn all of the comments, however I really enjoyed the article. It proved to be Very useful to me and I�m positive to all of the commenters here! It�s always nice when you can�t solely be told, but in addition entertained! I�m positive you had enjoyable penning this article."
"Thanks for posting! I really enjoyed the report. I�ve already bookmark this article."
"I like the valuable information you provide in your articles. I�ll bookmark your weblog and check again here frequently. I�m quite certain I�ll learn lots of new stuff right here! Best of luck for the next!"
"I recently came across your web site and have been reading along. I thought I would leave my very first comment. Nice blog! I will keep visiting this website very frequently."
"You got your point here, hehe, you surely did. In moments like this, I think that �the WEB� is the greatest invention of all human inventions. Or at least it�s most entertaining one!"
"Perhaps this is one of the most interesting blogs that I have ever seen. Interesting article, Funny comment. Keep it up!"
"Wonderful blog! I genuinely love how it is easy on my eyes and also the facts are well written. I am wondering how I may be notified whenever a new post has been made. I have subscribed to your rss feed which ought to do the trick! Have a nice day!"
"I think this is one of the most important information for me. And im glad reading your article. Good job, cheers"
"I was recommended this website by my cousin. I am not sure whether this post is written by him as no one else know such detailed about my problem. You are wonderful! Thanks!"
"Hello There. I found your blog using msn. This is an extremely well written article. I will be sure to bookmark it and return to read more of your useful info. Thanks for the post. I�ll certainly return."
"I like the valuable information you provide in your articles. I�ll bookmark your weblog and check again here frequently. I�m quite certain I�ll learn lots of new stuff right here! Best of luck for the next!"
"I had difficulty looking at this in Firefox but it works fine in IE. Anway, the content is good. I am very happy to have come across this."
"Thanks for the free info, good blog and I will be back again. Just thought I would let you know."
"I�m typically to blogging and i actually appreciate your content. The article has actually peaks my interest. I�m going to bookmark your site and keep checking for brand new information."
"I had difficulty looking at this in Firefox but it works fine in IE. Anway, the content is good. I am very happy to have come across this."
"I do agree with all the ideas you have presented in your post. They are very convincing and will definitely work. Thanks for the post."
"Wonderful blog! I genuinely love how it is easy on my eyes and also the facts are well written. I am wondering how I may be notified whenever a new post has been made. I have subscribed to your rss feed which ought to do the trick! Have a nice day!"
"Took me time to learn all of the comments, however I really enjoyed the article. It proved to be Very useful to me and I�m positive to all of the commenters here! It�s always nice when you can�t solely be told, but in addition entertained! I�m positive you had enjoyable penning this article."
"I usually don�t post in Blogs but your blog forced me to, awesome work, stunning"
"I always like to have a read about such things, my blog is related if you want to have a look round it please feel free. I have added yours to my bookmarks."
"Helpful information. Lucky me I found your site accidentally, and I am shocked why this coincidence did not took place in advance! I bookmarked it."
"Interesting read perhaps the best article iv e browse today We learn everyday cheers to you"
"I recently came across your web site and have been reading along. I thought I would leave my very first comment. Nice blog! I will keep visiting this website very frequently."
"Resources like the one you mentioned here will be very useful to me! I will post a link to this page on my blog. I am sure my visitors will find that very useful."
"Pretty nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I�ll be subscribing to your feed and I hope you write again soon!"
"You really make it seem so simple with your presentation but I find this topic before really hard to understand. It seems too complicated and very broad for me. I am looking forward for your next post."
"You really make it seem so simple with your presentation but I find this topic before really hard to understand. It seems too complicated and very broad for me. I am looking forward for your next post."
"Good blog, where did you come up with the knowledge in this piece of content? I�m glad I found it though, ill be checking back soon to see what other articles you have."
"Pretty nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I�ll be subscribing to your feed and I hope you write again soon!"
"Hi, very great web site you have made. I enjoyed reading this posting. I did want to publish a comment to tell you that the design of this site is very aesthetically sweet."
"This is very intreresting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your great post."useful."
"Oh my! Just delightful! Your writing manner is charming and the way you embraced the topic with grace is notable. I am intrigued, I make bold you are an expert on this subject. I am subscribing to your upcoming updates from now on."
"Thank you for the good writeup. It in fact was a amusement account it. Look advanced to far added agreeable from you! By the way, how could we communicate?"
"I think you have a great page here� today was my first time coming here.. I just happened to find it doing a google search. anyway, good post.. I�ll be bookmarking this page for sure."
"I like the valuable information you provide in your articles. I�ll bookmark your weblog and check again here frequently. I�m quite certain I�ll learn lots of new stuff right here! Best of luck for the next!"
"When i visit a blog, chances are that i get disappointed. Regarding your blog,I have to say that you have done a good job here."
"Perhaps this is one of the most interesting blogs that I have ever seen. Interesting article, Funny comment. Keep it up!"
"Hello blogger, good morning. Wonderful post. You have gained a new reader. Pleasee continue this awesome work and I look forward to more of your superb articles."
"This is very intreresting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your great post."useful."
"Hello blogger, good morning. Wonderful post. You have gained a new reader. Pleasee continue this awesome work and I look forward to more of your superb articles."