Java Reference
In-Depth Information
Live Collections
The node lists returned by the
document.getElementsByClassName()
and
docu-
ment.getElementsByTagName()
methods are
live
collections that will update to re-
flect any changes on the page. For example, if a new element with the class
swim
is added
or an existing one is removed, the node list updates automatically. Therefore, its use is dis-
couraged for performance reasons, but it can be useful.
To see an example of this, reload the page again to reset the DOM to its original state. Let's
take a look at how many elements are in the
sports
section:
var sports = document.getElementById("sports");
<< undefined
sports.children.length
<< 3
Now remove the
swim
paragraph:
var swim = document.getElementsByClassName('swim')[0];
<< undefined
sports.removeChild(swim);
<< <p class="swim">
sports.children.length
<< 2
You need to be careful when referring to elements by their index in a collection, as this can
change when markup is added or removed. For example, we saw earlier that the
run
para-
graph could be accessed using this line of code:
document.getElementsByTagName('p')[2];
<< undefined
