There are two ways to retrieve lists of elements
that live in the DOM. The first one is
document.querySelectorAll,
which returns a NodeList. The other is
document.getElementsByTagName, which
differs from document.querySelectorAll
in that you can only pass it a string with a tag name,
like "div"
or "a"
, and also in that it returns
an HTMLCollection.
Neither NodeLists nor HTMLCollections are true arrays, so they lack array methods such as forEach, but they do have some very interesting properties.
HTMLCollections are live nodes. This means that when changes are made to the DOM, the contents of an HTMLCollection can change without you having to call document.getElementsByTagName again.
To see how this works, try the following in the console.
var thumbnails = document.getElementsByTagName("a"); thumbnails.length;
After getting all of the anchor elements as an
HTMLCollection, you print the length
of that list to the console.
Now, remove some of the anchor tags from the page using the elements panel in the DevTools: Control-click (right-click) one of the list items and choose Delete element (Figure 6.29).
Do this several times, then enter thumbnails.length
into the console again. You should see
that the length
is different (Figure 6.30).
Converting NodeLists and HTMLCollections to arrays not only makes them more convenient to work with via array methods, but you also have the guarantee that the items in the array will not change, even if the DOM is modified.
3.135.247.11