IF I USE OBJECT.GETELEMENTSBYTAGNAME(TAGNAME) IN A FOR STATEMENT

marcel ethan

Total Post:105

Points:735
Posted by  marcel ethan
 1166  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. Pravesh Singh

    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++;

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!