Table of Contents
     NodeList
  HTMLCollection
  HTMLCollection和NodeList 实时性
  结语
Home Web Front-end HTML Tutorial DOM中的NodeList与HTMLCollection_html/css_WEB-ITnose

DOM中的NodeList与HTMLCollection_html/css_WEB-ITnose

Jun 24, 2016 am 11:34 AM

  最近在看《Javascript高级程序设计》的时候,看到了这样一句话:“理解NodeList和HTMLCollection,是从整体上透彻理解DOM的关键所在。”,所以觉得应该写一篇关于NodeList和HTMLCollection的博客来好好了解和总结下这方面的知识点。

     NodeList

  NodeList是一个节点的集合(既可以包含元素和其他节点),在DOM中,节点的类型总共有12种,通过判断节点的nodeType来判断节点的类型。

  我们可以通过Node.childNodes和document.querySelectAll() (返回NodeList的接口有很多,这里不一一列举,下同)来获取到一个NodeList对象。

  NodeList对象有个length属性和item()方法,length表示所获得的NodeList对象的节点个数,这里还是要强调的是节点,而item()可以传入一个索引来访问Nodelist中相应索引的元素。

 1 <body> 2     <div id="node"> 3         文本节点 4         <!-- 注释节点 --> 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) //     输出为914 </script>
Copy after login

  上面的HTML代码中,“文本节点”和父节点子节点的空格(连着的文本)算做一个文本节点,然后是一个注释节点和注释节点和元素节点之间的空格(换行会产生空格,空格算做文本节点)的文本节点,紧接着的是一个元素节点和元素节点之间的换行的文本节点,三个元素节点和元素节点间的两个文本节点,最后是最后得元素节点和父元素之间的空格产生的文本节点,总共是9个节点。

  NodeList对象的一大特点是它返回的内容是动态的(live),也就是说我们上面代码获取nodeLists是类似于“指针”的东西,所以在下面代码中我们在获取了nodeLists之后再向node中插入一个创建的span标签后,发现获取到了nodeLists.length变为10了,但是querySelectorAll这个接口返回的nodeList对象比较特殊,它是个静态(static)的对象。而且是元素的集合。

 1 <body> 2     <div id="node"> 3         文本节点 4         <!-- 注释节点 --> 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)  // 输出为1016     console.log(queryNodes.length)  //输出为317 </script>
Copy after login

  HTMLCollection

  HTMLCollection是元素集合,它和NodeList很像,有length属性来表示HTMLCollection对象的长度,也可以通过elements.item()传入元素索引来访问。当时它还有一个nameItem()方法,可以返回集合中name属性和id属性值得元素。HTMLDocument 接口的许多属性都是 HTMLCollection 对象,它提供了访问诸如表单、图像和链接等文档元素的便捷方式,比如document.images和document.forms的属性都是HTMLCollection对象。

 1 <body> 2     <img  src="/static/imghw/default1.png"  data-src="test.png"  class="lazy" id="image1" alt="DOM中的NodeList与HTMLCollection_html/css_WEB-ITnose" > 3     <img  src="/static/imghw/default1.png"  data-src="test.png"  class="lazy" id="image2" alt="DOM中的NodeList与HTMLCollection_html/css_WEB-ITnose" > 4     <img  src="/static/imghw/default1.png"  data-src="test.png"  class="lazy" id="image3" alt="DOM中的NodeList与HTMLCollection_html/css_WEB-ITnose" > 5     <img  src="/static/imghw/default1.png"  data-src="test.png"  class="lazy" id="image4" alt="DOM中的NodeList与HTMLCollection_html/css_WEB-ITnose" > 6     <img  src="/static/imghw/default1.png"  data-src="test.png"  class="lazy" id="image5" alt="DOM中的NodeList与HTMLCollection_html/css_WEB-ITnose" > 7     <img  src="/static/imghw/default1.png"  data-src="test.png"  class="lazy" id="image6" alt="DOM中的NodeList与HTMLCollection_html/css_WEB-ITnose" > 8 </body> 9 <script>10     console.log(document.images.namedItem('image1')) //<img  src="/static/imghw/default1.png"  data-src="test.png"  class="lazy" id="image1" alt="DOM中的NodeList与HTMLCollection_html/css_WEB-ITnose" >11 </script>
Copy after login

  HTMLCollection的集合和NodeList对象一样也是动态的,他们获取的都是节点或元素集合的一个引用。

  HTMLCollection和NodeList 实时性

  前面都说到了它们连个对象都不是历史文档状态的一个静态快照,而是实时性的,这个是一个非常令人惊讶的特性,它们能随着文档的改变而改变,这个是很值得我们注意的,我们在平常使用一些DOM 接口来返回一些DOM集合的时候,常常会忽视掉这些。

  HTMLCollection和NodeList的实时性非常有用,但是,我们有时要迭代一个NodeList或HTMLCollection对象的时候,我们通常会选择生成当前对象的一个快照或静态副本:

  

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

 这样的话,我们就可以放心的对当前的DOM集合做一些删减和插入操作,这个在DOM密集操作的时候很有用。

  还有MDN上面提到了一个将NodeList转化为Array的DOM扩展原型的方法(在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';});
Copy after login

  结语

  DOM最初设计是为了解析XML而设计的,之后沿用到HTML上。我们可以把DOM分为两部分 core 和 html,Core 部分提供最基础的 XML 解析API说明,HTML 部分专为 HTML 中的 DOM 解析添加其特有的 API。NodeList接口是在core中体现的,HTMLCollection则是在html部分,不同浏览器也会实现它们的不同接口,厂商联盟性质的规范组织出现会让这些更加规范,也不出现之前返回的是NodeList对象,但是却是静态的。

  这篇文章很多思想都是自己在平时和网上了一些博客中了解到了,其中加了很多自己的组织和理解,目的在于梳理下一些比较深入的知识点,如果写的有疏漏和错误之处,还请指出。

 

  

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

HTML: The Structure, CSS: The Style, JavaScript: The Behavior HTML: The Structure, CSS: The Style, JavaScript: The Behavior Apr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML, CSS, and JavaScript: Web Development Trends The Future of HTML, CSS, and JavaScript: Web Development Trends Apr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

The Future of HTML: Evolution and Trends in Web Design The Future of HTML: Evolution and Trends in Web Design Apr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative Overview HTML vs. CSS vs. JavaScript: A Comparative Overview Apr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Building the Structure of Web Pages HTML: Building the Structure of Web Pages Apr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

The Role of HTML: Structuring Web Content The Role of HTML: Structuring Web Content Apr 11, 2025 am 12:12 AM

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

HTML: Is It a Programming Language or Something Else? HTML: Is It a Programming Language or Something Else? Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

See all articles