Skip to content

Instantly share code, notes, and snippets.

@shawnchin
Created November 16, 2010 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shawnchin/701652 to your computer and use it in GitHub Desktop.
Save shawnchin/701652 to your computer and use it in GitHub Desktop.
// return data-* attributes of a node as a dict
function getDataAttributes(node) {
var vstr = $().jquery.split(".");
var v0 = parseInt(vstr[0]) || 0,
v1 = parseInt(vstr[1]) || 0,
v2 = parseInt(vstr[2]) || 0;
// jQuery >= 1.4.4 has built in op to do this.
if ( v0 > 1 || (v0 == 1 && v1 > 4) || (v0 == 1 && v1 == 4 && v2 >= 4)) {
return node.data();
}
// for jQuery < 1.4.4, work it out ourselves,
var d = {}, re_dataAttr = /^data\-(.+)$/;
$.each(node.get(0).attributes, function(index, attr) {
if (re_dataAttr.test(attr.nodeName)) {
var key = attr.nodeName.match(re_dataAttr)[1];
d[key] = attr.nodeValue;
}
});
// merge in data added/modified via $.fn.data (>1.4 only)
if (v0 == 1 && v1 == 4)) { $.extend(d, node.data()); }
return d;
}
@NickCraver
Copy link

I'd just do if($.fn.jquery > "1.4.4") since it's a string.

@ZhangYiJiang
Copy link

In addition to what Nick Craver said, I'm also curious as to why you're trying to create a version independent function, when one version of jQuery is every going to be used on a page (and most likely for the entire project). The overhead of including the additional function is not insignificant considering that one of the two will certainly never be used.

This is of course a moot point if you decide to not use jQuery.fn.data because of the way it parses the attributes.

Related chat transcript: http://chat.stackoverflow.com/transcript/message/118676#118676

@shawnchin
Copy link
Author

@NickCraver: Lacking experience with javascript, I was just being overly cautious. The worry I had at time of writing was that a straight forward string compare would be invalid once we get double digit version numbers, e.g. "1.10.1" or "1.4.10".

@shawnchin
Copy link
Author

@ZhangYiJiang: I attempted to make it version independent as it's part of a plugin that I plan to use in different projects (one of which were developed against 1.4.2 and not tested with 1.4.4). However, I do see your point.

In retrospect, it does seem rather pointless to include both approaches when one would work for both pre/post 1.4.4 versions.

Many thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment