javascripthtmlgetelementsbyclassname

Element ID from document.getElementsByClassName


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?


Solution

  • 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 accomplish what you want:

    for (const node of document.getElementsByClassName("popField")) {
      node.innerHTML = node.id;
    }