zoukankan      html  css  js  c++  java
  • JavaScript使用childNodes和children

      childNodes用来获取一个元素的所有子元素,这个包括元素节点和文本节点。

      children用来获取一个元素的子元素节点,注意只是元素节点

    其中DOM中常见的三种节点分别如下:

      元素节点:<body>,<p>,<a>,<div>,<head>.....等等这些标签,都是元素节点

      属性节点:title,value,href,id,class等等这些标签的属性,都是属性节点

      文本节点:文本节点是包含在在标签之内的内容(双标签)比如<p>this is text node</p>,中间的文字就是文本节点;注意包含在标签中间的不一定是文本节点,比如<div><p></p></div>当中的<p>是元素节点

      所以在使用childNodes来获取到一个元素的子元素集合,这是一个数组。

      其中最常用的是通过childNodes获得的对象数组中,第一个子元素对象(也即下标为0),这个元素是text,即文本节点,也可以使用firstChild来替代childNodes[0],然后通过nodeValue属性来获取text的值。

      如果在标签之中只有一个文本节点,而没有其他元素节点时,也可以使用innerHTML来获取这个节点的文本内容。

    具体的用法如下:

    <body>
    	<div id="test">
    		this is test
    		<p>this is other test</p>
    	</div>
    </body>
    <script>
    	var div = document.getElementById("test");
    
    	alert(div.childNodes.length);        //显示3
    
    	alert(div.childNodes[0]);	//[object Text]
    
    	alert(div.childNodes[0].nodeValue);   //显示this is test
    	//等价
    	alert(div.firstChild.nodeValue);      //显示this is test
    
    	alert(div.childNodes[1]);	//[object HTMLParagraphElement]
    
    	alert(div.childNodes[1].childNodes[0].nodeValue); //this is other test
    	//等价	
    	alert(div.childNodes[1].firstChild.nodeValue); //this is other test
    	//p标签中无其他节点,可以使用innderHTML
    	alert(div.childNodes[1].innerHTML);  ////this is other test
    
    </script>
    

      

      

  • 相关阅读:
    zepto.js介绍
    box-sizing属性
    响应式网页高度自适应原理
    固定-比例-固定
    常用的js正则验证
    mysql之连接查询(多表查询)
    数据约束
    mysql表数据的增删改查
    mysql学习之数据库管理与表管理
    滑动选项卡的制作
  • 原文地址:https://www.cnblogs.com/-beyond/p/8433576.html
Copyright © 2011-2022 走看看