Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Get data-type tag value

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.

like image 489
ryandlf Avatar asked May 23 '26 04:05

ryandlf


2 Answers

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');
}
like image 131
Joseph Avatar answered May 25 '26 18:05

Joseph


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;
like image 26
Zach Saucier Avatar answered May 25 '26 18:05

Zach Saucier