美文网首页
总结遍历 DOM Tree 的方法

总结遍历 DOM Tree 的方法

作者: 饥人谷_曾涛 | 来源:发表于2016-08-18 14:51 被阅读201次

    根节点

    1. document.documentElement返回文档对象( document )的根元素
    2. document.head( <head>标签 )
    3. document.body( <body>标签 )

    遍历节点

    父节点:parentNode
    子节点:childNodes
    子元素节点:children
    前一个兄弟节点:previousSibling
    后一个兄弟节点:nextSibling
    第一个子节点:firstChild
    第一个子元素节点:firstElementChild
    最后一个子节点:lastChild( 可以是任何类型的节点 )
    最后一个子元素节点:lastElementChild
    返回一个节点的根元素:ownerDocument

    节点信息

    节点类型:nodeType( 返回一个数字值 )
    节点名字:nodeName( 元素节点返回大写 )
    节点内容:nodeValue

    获取所有节点的方法

    • 方法 1 ( 递归遍历childNodes )
    var elemArr = [];
    function ergodic(child) {
      for (var i = 0, len = child.length; i < len; i++) {
        if (child[i].nodeType === 1) {
          elemArr[elemArr.length] = child[i];
          if (child[i].childNodes.length > 0) {
            ergodic(child[i].childNodes);
          }
        }
      }
    }
    
    • 方法 2 ( 递归遍历children )
    var elemArr = []
    function ergodic(child) {
      for (var i = 0, len = child.length; i < len; i++) {
        elemArr[elemArr.length] = child[i];
        if (child[i].children.length > 0) {
          ergodic(child[i].children);
        }
      }
    }
    

    相关文章

      网友评论

          本文标题:总结遍历 DOM Tree 的方法

          本文链接:https://www.haomeiwen.com/subject/ysrvsttx.html