Javascript Get value of datatype tag

I would like to get data-type

which is the new HTML5 tag name (or any custom tag name), with pure javascript. The context in which I need to access this data is inside the childNodes element loop.

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 a prototype way childNodes

so that any element rendered using this tag has a function attached to it dataType

, so that this code actually works?

I suppose I would need to use children[i].outerHTML

to get the raw HTML element and then a regex to actually put the value from that element.

+3


source to share


2 answers


if you want to get data from attributes data-*



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

for(var i=0; i<childrenLength; i++) {
    var dataType = children[i].getAttribute('data-type');
}

      

+6


source


If you look at the Mozilla doc on the subject, you will find that the standard defines an easier way than .getAttribute

: a DOMStringMap , which can be read using the dataset property .

In short, you can do this

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

      



Or you can set dataset

for a variable like below, which is handy when you are getting multiple data attributes from an element

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

      

+1


source







All Articles