Home > DeveloperSection > Forums > If I use object.getElementsByTagName(tagName) in a for statement
marcel ethan
marcel ethan

Total Post:105

Posted on    August-12-2013 1:04 AM

 JavaScript JavaScript 

 1 Reply(s)
 877  View(s)
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.

Pravesh Singh

Total Post:411

Posted on    August-12-2013 1:08 AM

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;



  elements[index].property = value;



Don't want to miss updates? Please click the below button!

Follow MindStick