In-depth understanding of dynamic collections--nodelist, Htmlcollection, and NamedNodeMap in JavaScript

Source: Internet
Author: User

NodeList

The NodeList instance object is a class array object whose members are node objects, including the ChildNodes and Queryselectorall () method return values

<div id= "Test" ></div><script>console.log (test.childnodes),//[]//ie7-Browser does not define NodeList object, will error, Other browsers return Trueconsole.log (test.childnodes instanceof NodeList) </script>
<div id= "Test" ></div><script>console.log (Document.queryselectorall (' div '));//[div#test]// ie8-Browser does not support Queryselectorall () method, returns false, other browsers return Trueconsole.log (Document.queryselectorall (' div ') instanceof NodeList) </script>

A dynamic collection is a change in the DOM structure that can be automatically reflected in the saved object

<div id= "Test" ></div><script>var childn = Test.childnodes;console.log (ChildN);//[] Test.appendchild (document.createelement (' div ')); Console.log (CHILDN);//[div]</script>

Static

Note NodeList are not all dynamic collections, where the Queryselectorall () return value is a static collection nodestaticlist

<div id= "Test" ></div><script>var Seles = Test.queryselectorall (' div '); Console.log (Seles);//[] Test.appendchild (document.createelement (' div ')); Console.log (Seles);//[]console.log (' div ' ));//[div]</script>

Array

Since nodelist is a class array object and not a real array object, you can use the slice () method to turn it into a real array

<div id= "Test" ></div><script>var childn = Test.childnodes;console.log (ChildN instanceof Array);// Falsevar childnew = Array.prototype.slice.call (CHILDN); Console.log (childnew instanceof Array);//true</script>

However, because the Ie8-browser implements nodelist as a COM object and cannot use the Array.prototype.slice () method, all members must be manually enumerated

<div id= "Test" ></div><script>var childn = Test.childnodes;console.log (ChildN instanceof Array);// Falsefunction Converttoarray (nodes) {    var array = null;    try{        array = Array.prototype.slice.call (nodes)    }catch (ex) {        array = [];        var len = nodes.length;        for (var i = 0; i < len; i++) {            array.push (nodes[i]);        }    }    return array;} var childnew = Converttoarray (CHILDN); Console.log (childnew instanceof Array);//true</script>

Htmlcollection

The Htmlcollection object is similar to the NodeList object and is also a collection of nodes, returning a class array object. But the two are different.

The NodeList collection is primarily a collection of node nodes, while the Htmlcollection collection is primarily a collection of element node nodes. There are 12 node nodes, and element node is just one of them. More information about 12 node types at this point

The Htmlcollection collection includes return values for methods such as getElementsByTagName (), Getelementsbyclassname (), Getelementsbyname (), and children, Document.links, document.forms and other elements collection

<div id= "Test" ></div><script>var childn = test.children;//ie7-Browser does not define Htmlcollection object, will error, Other browsers return Trueconsole.log (childn instanceof htmlcollection); var tags =test.getelementsbytagname (' div ');// ie7-Browser does not define Htmlcollection object, will error, other browsers return Trueconsole.log (Tags instanceof htmlcollection);</script>    

Dynamic

Unlike NodeList objects, all Htmlcollection objects are dynamic

<div id= "Test" ></div><script>var childn = Test.children;var tags =test.getelementsbytagname (' div ') ; Console.log (childn,tags);//[], []test.innerhtml = ' <div></div> '; Console.log (childn,tags);//[div], [ Div]</script>    

[note] Like the NodeList object, to become a true array object, you need to use the slice () method, in Ie8-browser, you must manually enumerate all the members

NamedNodeMap

Some people may not have heard of the NamedNodeMap object, the object's common instance object is the Attributes property

<div id= "Test" ></div><script>var attrs = Test.attributes;console.log (attrs instanceof NamedNodeMap );//true</script>

Dynamic

The object is also a dynamic collection

<div id= "Test" ></div><script>var attrs = Test.attributes;console.log (attrs);//NamedNodeMap {0:id, Length:1}test.setattribute (' title ', ' 123 '); Console.log (attrs);//namednodemap {0:id, 1:title, Length:2}</script >

Precautions

Dynamic collections are a useful concept, but be careful when using loops. May cause a dead loop due to ignoring the dynamic nature of the collection

var divs = document.getelementsbytagname ("div"); for (var i = 0; i < divs.length; i++) {    Document.body.appendChild (d Ocument.createelement ("div"));}

In the above code, since DIVs is a HtmlElement collection, Divs.length will continue to grow with the appendchild () method, thus becoming a dead loop

In order to avoid this situation, it can generally be written in the form below

var divs = document.getelementsbytagname ("div"); for (var i = 0,len = Divs.length; i < Len; i++) {    Document.body.appen Dchild (document.createelement ("div"));}

In general, to minimize the number of visits to NodeList, Htmlcollection, NamedNodeMap. Because each time they are accessed, a document-based query is run. Therefore, you might consider caching their values.

At last

NodeList is a collection of nodes, Htmlcollection is a collection of element nodes, and NamedNodeMap is a collection of attribute nodes, all of which are class array objects

Yes, there is a more classic class array object-The arguments inside the function, which is also dynamic

PS: Original https://www.cnblogs.com/xiaohuochai/p/5827389.html

In-depth understanding of dynamic collections--nodelist, Htmlcollection, and NamedNodeMap in JavaScript

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.