admin管理员组文章数量:1295915
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.
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.
2 Answers
Reset to default 8if 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;
本文标签: htmlJavascript Get datatype tag valueStack Overflow
版权声明:本文标题:html - Javascript Get data-type tag value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741627199a2389152.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论