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 badges
Add a ment  | 

1 Answer 1

Reset to default 4

Using 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