If I use object.getElementsByTagName(tagName) in a for statement

Total Post:104

Points:728
 1472  View(s)
Ratings:
Rate this:

If I use object.getElementsByTagName(tagName) in a for statement,

for (index = 0; index < object.getElementsByTagName(tagName).length; index++) {

object.getElementsByTagName(tagName)[index].property = value;

}

Does the browser instantiate a new nodeList object for every pass through the loop, or does thebrowser simply refer to a single generated list every time, or maybe it instantiates a list, references the object specified and unloads the list object every pass through the loop?

I've been wondering if its better to store the nodeList object to a variable and reference it when neened.

  1. Post:412

    Points:2888
    Re: If I use object.getElementsByTagName(tagName) in a for statement

    Your browser is generating a new list each time. But this code will work as index is changing every run.

    It is a good practice to first save node list in some var:

    var index = 0;
    while(index<object.getElementsByTagName(tagName))
    {
      elements[index].property = value;
      index++;
    }

      Modified On Mar-30-2018 06:34:58 AM

Answer