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.
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');
}
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;