For the More Curious: NodeLists and HTMLCollections

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).

Figure 6.29  Deleting a DOM element with the DevTools

Deleting a DOM element with the DevTools

Do this several times, then enter thumbnails.length into the console again. You should see that the length is different (Figure 6.30).

Figure 6.30  The length value changes after deleting elements

The length value changes after deleting elements

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.100.237