admin管理员组文章数量:1323714
Relatively new to JS/Ajax, so I may be missing something obvious here. Let's say at some point in javascript I run ajax to get a number of div elements with a certain class name. I then want to retrieve the html id tag from each of these elements and do something with that information (say populate the element), something like so.
var divstopop = document.getElementsByClassName("popField"),x;
for(x in divstopop){
divstopop[x].innerHTML= x.id; //x.id or something?
}
Is this in any way possible to do?
Relatively new to JS/Ajax, so I may be missing something obvious here. Let's say at some point in javascript I run ajax to get a number of div elements with a certain class name. I then want to retrieve the html id tag from each of these elements and do something with that information (say populate the element), something like so.
var divstopop = document.getElementsByClassName("popField"),x;
for(x in divstopop){
divstopop[x].innerHTML= x.id; //x.id or something?
}
Is this in any way possible to do?
Share Improve this question edited Jan 31, 2013 at 7:09 Ja͢ck 174k39 gold badges266 silver badges314 bronze badges asked Jan 31, 2013 at 6:40 oIovoIooIovoIo 891 gold badge3 silver badges10 bronze badges1 Answer
Reset to default 4Using in
is not how you should iterate over an array of elements. You should use the .length
property and use numeric indexing:
for (var i = 0; i < divstopop.length; ++i) {
// Get id property from element and set as innerHTML
divstopop[i].innerHTML = divstopop[i].id;
}
With the introduction of ES6, you can also use for ... of
to acplish what you want:
for (const node of document.getElementsByClassName("popField")) {
node.innerHTML = node.id;
}
本文标签: javascriptElement ID from documentgetElementsByClassNameStack Overflow
版权声明:本文标题:javascript - Element ID from document.getElementsByClassName - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742128080a2422033.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论