Get list of data-* attributes using javascript / jQuery -
given arbitrary html element 0 or more data-*
attributes, how can 1 retrieve list of key-value pairs data.
e.g. given this:
<div id='prod' data-id='10' data-cat='toy' data-cid='42'>blah</div>
i able programmatically retrieve this:
{ "id":10, "cat":"toy", "cid":42 }
using jquery (v1.4.3), accessing individual bits of data using $.data()
simple if keys known in advance, not obvious how 1 can arbitrary sets of data.
i'm looking 'simple' jquery solution if 1 exists, not mind lower level approach otherwise. had go @ trying to parse $('#prod').attributes
lack of javascript-fu letting me down.
update
customdata need. however, including jquery plugin fraction of functionality seemed overkill.
eyeballing source helped me fix own code (and improved javascript-fu).
here's solution came with:
function getdataattributes(node) { 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; } }); return d; }
update 2
as demonstrated in accepted answer, solution trivial jquery (>=1.4.4). $('#prod').data()
return required data dict.
actually, if you're working jquery, of version 1.4.3 1.4.4 (because of bug mentioned in comments below), data-*
attributes supported through .data()
:
as of jquery 1.4.3 html 5
data-
attributes automatically pulled in jquery's data object.note strings left intact while javascript values converted associated value (this includes booleans, numbers, objects, arrays, , null).
data-
attributes pulled in first time data property accessed , no longer accessed or mutated (all data values stored internally in jquery).
the jquery.fn.data
function return of data-
attribute inside object key-value pairs, key been part of attribute name after data-
, value been value of attribute after been converted following rules stated above.
i've created simple demo if doesn't convince you: http://jsfiddle.net/yijiang/wvfsg/
Comments
Post a Comment