NodeList, HTMLCollection, and nodelist in DOM

Source: Internet
Author: User

NodeList, HTMLCollection, and nodelist in DOM

Recently, when reading Javascript advanced programming, I saw the following sentence: "Understanding NodeList and HTMLCollection is the key to a complete understanding of DOM .", Therefore, I think we should write an article about NodeList and HTMLCollection to better understand and summarize this knowledge point.

NodeList

NodeList isSet of nodes(It can contain elements and other nodes). In DOM, there are a total of 12 node types, and the node type is determined by judging the node's nodeType.

We can get a NodeList object through Node. childNodes and document. querySelectAll () (there are many interfaces that return NodeList, which are not listed here, the same below.

The NodeList object has a length attribute and the item () method. length indicates the number of nodes of the obtained NodeList object. Here we still need to emphasize nodes, while item () you can input an index to access the corresponding index elements in Nodelist.

1 <body> 2 <div id = "node"> 3 text node 4 <! -- Comment nodes --> 5 <span> node1 </span> 6 <span> node2 </span> 7 <span> node3 </span> 8 </div> 9 </ body> 10 <script> 11 var node = document. getElementById ('node'), 12 nodeLists = node. childNodes13 console. log (nodeLists. length) // The output is 914 </script>

 

In the preceding HTML code, the space between the "text node" and the child node of the parent node (connected text) is counted as a text node, then there is a text node between a comment node and an element node (a space is generated when a line feed occurs, and a space is counted as a text node, next is a text node with line breaks between an element node and an element node, and two text nodes between the three element nodes and the element node, the last is the text node generated by space between the final element node and the parent element. There are 9 nodes in total.

A major feature of the NodeList object is that the returned content is dynamic (live). That is to say, the above Code obtains nodeLists, which is something similar to a "pointer, therefore, in the following code, we inserted a created span tag to node after obtaining nodeLists, and found that nodeLists was obtained. the length is changed to 10, but the nodeList object returned by the querySelectorAll interface is special. It is a static object. And yesElement Set.

1 <body> 2 <div id = "node"> 3 text node 4 <! -- Comment nodes --> 5 <span> node1 </span> 6 <span> node2 </span> 7 <span> node3 </span> 8 </div> 9 </ body> 10 <script> 11 var node = document. getElementById ('node') 12 var nodeLists = node. childNodes13 var queryNodes = node. querySelectorAll ('span ') 14 node. appendChild (document. createElement ('span ') 15 console. log (nodeLists. length) // The output is 1016 console. log (queryNodes. length) // The output is 317 </script>
HTMLCollection

HTMLCollection is a collection of elements. It is similar to NodeList and has the length attribute to indicate the length of the HTMLCollection object. You can also use elements. item () to input element indexes to access the object. At that time, it also had a nameItem () method, which can return the name attribute and id attribute value element in the collection. Many attributes of the HTMLDocument interface are HTMLCollection objects. It provides convenient methods to access document elements such as forms, images, and links. For example, attributes of document. images and document. forms are HTMLCollection objects.

 1 <body> 2      3      4      5      6      7      8 </body> 9 <script>10     console.log(document.images.namedItem('image1')) //11 </script>

The collection of HTMLCollection is also dynamic like the NodeList object. they obtain a reference of a node or element set.

HTMLCollection and NodeList Timeliness

As mentioned above, even objects are not static snapshots of history documents, but are real-time. This is a very surprising feature that can change as documents change, this is worth noting. We often ignore this when using some DOM interfaces to return some DOM sets.

HTMLCollection and NodeList are very useful in real time. However, when we sometimes need to iterate A NodeList or HTMLCollection object, we usually choose to generate a snapshot or static copy of the current object:

  

1 var staticLists = Array.prototype.slice.call(nodeListorHtmlCollection, 0)

In this way, we can safely delete and insert the current DOM set, which is useful in DOM intensive operations.

Also, MDN mentioned above a method for converting NodeList into an Array DOM extension prototype (dangerous in IE6/7: http://perfectionkills.com/whats-wrong-with-extending-the-dom ):

var arrayMethods = Object.getOwnPropertyNames( Array.prototype );arrayMethods.forEach( attachArrayMethodsToNodeList );function attachArrayMethodsToNodeList(methodName){  if(methodName !== "length") {    NodeList.prototype[methodName] = Array.prototype[methodName];  }};var divs = document.getElementsByTagName( 'div' );var firstDiv = divs[ 0 ];firstDiv.childNodes.forEach(function( divChild ){  divChild.parentNode.style.color = '#0F0';});
Conclusion

DOM was initially designed to parse XML and then followed by HTML. We can divide the DOM into two parts: core and html. The Core part provides the basic XML parsing API description, and the HTML part adds its unique API for DOM parsing in HTML. The NodeList interface is embodied in the core, while the HTMLCollection interface is in the html part. Different browsers also implement different interfaces. The standardized organization of the vendor Alliance nature will make these more standardized, it does not appear that the previously returned NodeList object, but it is static.

Many of the ideas in this article are learned by myself in my usual and online blogs, and I have added my own organization and understanding in order to sort out some in-depth knowledge points, if any omission or error occurs, please note.

 

  

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.