zoukankan      html  css  js  c++  java
  • children和childNodes 的区别

    1、childNodes 属性,标准的,它返回指定元素的子元素集合,包括html节点,所有属性,文本。可以通过nodeType来判断是哪种类型的节点,只有当nodeType==1时才是元素节点,2是属性节点,3是文本节点,8是注释节点。

    有些人错误的使用()去取该集合元素,下表列出各浏览器对childNodes(i)的支持情况:

      IE6/7/8 Firefox3.5 Safari4 Chrome4 Opera10
    childNodes(i) 支持 不支持 支持 支持 支持

      2、有时候需要获取指定元素的第一个html子节点(非属性/文本节点),最容易想到的就是firstChild 属性。代码中第一个html节点前如果有换行,空格,那么firstChild返回的就不是你想要的了。可以使用nodeType来判断下。

    1. function getFirst(elem){  
          for(var i=0,e;e=elem.childNodes[i++];){  
              if(e.nodeType==1)  
                  return e;  
          }         
      }  

     3、通过nodeType来判断是哪种类型的节点,达到效果兼容。

    <ul id="ul1">
        <li><span>dgfgfhgh</span></li>
        <li></li>
        <li></li>
    </ul>
    window.onload=function(){
        oUl1=document.getElementById("ul1");
       // alert(oUl1.childNodes.length);    //7
        for(var i=0; i<oUl1.childNodes.length; i++){
            if(oUl1.childNodes[i].nodeType==1){
                oUl1.childNodes[i].style.background='red';
            }
        }

    4、children 属性,非标准的,它返回指定元素的子元素集合。经测试,它只返回html节点,甚至不返回文本节点。且在所有浏览器下表现惊人的一致。和childNodes 一样,在firefox下不支持()取集合元素。因此如果想获取指定元素的第一个html节点,可以使用children[0]来替代上面的getFirst函数。需注意children在IE中包含注释节点。

    <ul id="ul1">
        <li><span>dgfgfhgh</span></li>
        <li></li>
        <li></li>
    </ul>
    window.onload=function(){
        oUl1=document.getElementById("ul1");
        //alert(oUl1.children.length);  //3
        for(var i=0; i<oUl1.children.length; i++){
            oUl1.children[i].style.background='red';
        }
    }
  • 相关阅读:
    华为机试测试- 最小公倍数
    华为机试测试- 字符串最长的数字串
    华为机试测试- 大数相加
    Java 字符串倒序
    java BigDecimal
    华为机试测试-验证尼科彻斯定理
    华为机试测试-矩阵乘法-循环
    JAVA使用脚本引擎执行JS
    javascript学习之位置获取
    javascript学习笔记之DOM
  • 原文地址:https://www.cnblogs.com/hjbky/p/6228811.html
Copyright © 2011-2022 走看看