Javascript Get data-type tag value

Go To StackoverFlow.com

3

I would like to be able to retrieve the data-type, which is a new HTML5 tag name (or any custom tag name for that matter) with pure javascript. The context in which I would need to access this data is from within a loop of an elements childNodes.

var children = document.getElementById('foo').childNodes;
for(var i=0; i<children.length; i++) {
    var dataType = children[i].dataType //This does not work.
}

Is there some way to prototype childNodes so that any element retrieved with that tag will have a dataType function attached to it so that the above code would in fact work?

I figure I'll have to use children[i].outerHTML to get the element's raw HTML and then a regular expression to actually put the value from the element.

2012-04-04 06:09
by ryandlf


6

if you mean getting data from data-* attributes

var children = document.getElementById('foo').childNodes;
var childrenLength = children.length;

for(var i=0; i<childrenLength; i++) {
    var dataType = children[i].getAttribute('data-type');
}
2012-04-04 06:13
by Joseph
Or that. Looks alot easier than my approach haha - ryandlf 2012-04-04 06:38


1

If you check out Mozilla's docs on the subject, you'll find that the standard defines a simpler way than .getAttribute: a DOMStringMap which can be read using a dataset property.

In short that means that you can do this

var dataType = children[i].dataset.dataType;

Or you can set the dataset to a variable like the following, which is handy when you're getting several data attributes from an element

var dataSet = children[i].dataset,
    dataType = dataSet.dataType;
2014-07-05 18:19
by Zach Saucier
Ads