You may not have heard of DOM operations in js and this: HTMLCollection and NodeList

Posted by Altec on Wed, 05 Jan 2022 20:38:13 +0100


⛱️ preface

I still remember the last interview when I was asked about the relationship between htmlCollection and array. At that time, I was thinking about the relationship between sets and arrays in html. That is to say, the relationship between sets and arrays?

So... The interviewer immediately corrected me that htmlCollection is a combination of words and a part of js. At that time, I probably wanted to... Find a hole drill

No, I still have to accept it with an open mind. It's more reasonable to check leaks and fill vacancies. After a series of data query and summary, the following summary is obtained.

Let's start with the explanation of this article~ πŸ™‹

🎈 1, Basic knowledge

1. Definitions

(1)HTMLCollection

  • HTMLCollection represents a collection (general collection) containing elements (the order of elements is the interface in the document flow), and also provides attributes and methods to select elements from the collection.
  • For example, using the getElementsByTagName() method returns an HTMLCollection object.

(2)NodeList

  • The NodeList object is a collection of nodes.

  • The NodeList object can be obtained by the following methods. β‘  there are some methods in the old version of HTMLCollection object, such as getelementslist (), but not in the old version of HTMLCollection object. β‘‘ Nodes for all browsers The childNodes property returns all NodeList objects. β‘’ Document. For most browsers Queryselectorall() returns a NodeList object.

  • We can verify with the following code:

    document.body.childNodes instanceof NodeList // true
    document.querySelector('body') instanceof NodeList // true or false
    document.getElementByClassName('body') instanceof NodeList // true or false
    

2. Properties and methods

(1)HTMLCollection

Properties and methods in HTMLCollection objects, for example:

  • item(index) -- returns the element with the specified index in the HTMLCollection. If it does not exist, it returns null;
  • length (read only) -- returns the number of elements in the HTML collection.

Next, an example is used to illustrate the verification. The specific codes are as follows:

document.getElementsByTagName('body') instanceof HTMLCollection // true

const htmlCollection = document.getElementsByTagName('body')
console.log(htmlCollection.item(0)) // <body>...</body>
console.log(htmlCollection.length()) // 1

(2)NodeList

The properties and methods in the NodeList object mainly include the following. include:

  • item() -- returns the index of an element based on the number of documents;
  • length() -- returns the number of nodes in the NodeList;
  • NodeList.forEach() -- this method is used to traverse all members in NodeList. It receives a callback function as a parameter and executes the callback function every time it traverses. The usage is completely consistent with the forEach method of the array instance;
  • NodeList.keys()/values()/entries() -- for these three methods, they will return an ES6 ergodic object, which can be iterated through for... Of... To obtain the information of each member.

At the same time, pay attention to the differences between the above three, as follows:

  • keys() -- refers to the traverser that returns the key name;
  • values() -- refers to the traverser that returns the key value;
  • entries() -- it means that the returned iterator should contain both key name and key value information.

Let's write some code to demonstrate the above. The specific codes are as follows:

const nodelist = document.querySelectorAll('body')

console.log(nodelist.item(0)) // <body>...</body>
console.log(nodelist.length) // 1
console.log(nodelist.forEach(item => console.log(item))) // <body>...</body>

for(var key of nodelist.keys()) {
  console.log(nodelist[key]) // <body>...</body>
}

for(var value of nodelist.values()) {
  console.log(value) // <body>...</body>
}

for(var entry of nodelist.entries()) {
  console.log(entry) // [0, body]
}

πŸͺ 2, Similarities and differences

1. Difference between htmlcollection and NodeList

HTMLCollectionNodeList
aggregateCollection of elementsCollection of nodes
Static and dynamicHTMLCollection is dynamically bound and a dynamic collection. When the DOM tree changes, the HTMLCollection will also change, indicating that the addition and deletion of its nodes are sensitiveNodeList is a static collection, which is not affected by changes in DOM tree elements; This is equivalent to a snapshot of the DOM tree, the number and type of nodes, that is, the NodeList cannot feel when adding or deleting nodes. However, you can feel the modification of the internal content of the node, such as modifying innerHTML
nodeDoes not contain attribute nodes and text nodesOnly NodeList objects have nodes that contain attributes and text
Element acquisition methodThe HTMLCollection element can be obtained by name, id, or index indexNodeList can only be obtained by index index
Pseudo arrayHTMLCollection and NodeList are class arrays, not arrays, but just look like arrays. Therefore, array methods, such as pop(), push(), or join(), cannot be usedSame as HTMLCollection

2. The difference between queryselectorall and getElementsByTagName

In the above table, we can see that HTMLCollection is a dynamic collection. When the DOM tree changes, the HTMLCollection will also change. NodeList is a static collection. When the DOM tree changes, NodeList will not be affected by the DOM tree changes. Let's give two examples.

(1)querySelectorAll

Attach the code first:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>htmlCollection and NodeList</title>
</head>
<body>
    <ul>
        <li></li>
        <li></li>
        <li>MondayLab</li>
        <li></li>
        <li></li>
    </ul>
    <script>
        var oldUl = document.querySelectorAll('ul')[0];
        var oldLi = document.querySelectorAll('li');

        console.log(oldUl); // NodeList[body]
        console.log(oldLi.length); // 5

        var newLi = document.createElement('li');
        oldUl.appendChild(newLi);

        console.log(oldLi.length); // 5
        var length = oldLi.length - 1;
        oldLi[length].innerHTML = 'monday';
        console.log(oldLi[length].innerHTML); // monday 
        console.log(oldLi.length); // 5 → although the content of the text node can be read through innerHTML, the length remains unchanged, still 5
    </script>
</body>
</html>

As you can see, using querySelectorAll to get < li >, a collection of nodelists is returned. And when the page DOM structure changes, its length will not change. However, when innerHTML is changed, the content of the text node will change. It is worth noting that even if innerHTML changes the structure of DOM, the length remains unchanged, or 5.

(2)getElementsByTagName

Attach the code first:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTMLCollection</title>
</head>
<body>
    <ul>
        <li></li>
        <li></li>
        <li>MondayLab</li>
        <li></li>
        <li></li>
    </ul>
    <script>
        var oldUl = document.getElementsByTagName('ul')[0];
        var oldLi = document.getElementsByTagName('li');

        console.log(oldUl); // HTMLCollection[body]
        console.log(oldLi.length); // 5

        var newLi = document.createElement('li');
        oldUl.appendChild(newLi);

        console.log(oldLi.length); // 6 → successfully change the structure of DOM
    </script>
</body>
</html>

You can see that when getElementByTagName is used, an HTMLCollection collection is obtained. This means that when adding or deleting nodes, the DOM structure of the page will change, and the HTMLCollection will obtain the length of the collection in real time.

πŸ“ž 3, Conclusion

When I write here, I have to feel that js's DOM operation is so powerful, and I suddenly understand why I encountered so many holes when writing code before. If you trace back to the principle at the beginning of learning, you should be able to jump a lot less pits.

At this point, the content about HTMLCollection and NodeList is over! I hope it will help you~

There are several articles I have read that are easy to understand. If necessary, I can expand my knowledge~

🐣 One More Thing

(: references)

lio_zeroπŸ‘‰Difference between HTMLCollection and NodeList

SnandyπŸ‘‰Convert HTMLCollection/NodeList / pseudo array to array

binyellowπŸ‘‰DOM operation, HTMLCollection, NodeList

love of effect πŸ‘‰ NodeList and HTMLCollection

(: Fan Wai Pian)

  • Pay attention to the official account of Monday's research room. First, we will focus on quality articles.

  • If this article is useful to you, remember to leave a footprint jio before you go~

  • The above is the whole content of this article! See you next time! πŸ‘‹πŸ‘‹πŸ‘‹

Topics: Javascript Front-end DOM