JSDom操作

转自 知行网

lement Traversal规范中的firstElementChild、lastElementChild、previousElementSibling、nextElementSibling、childElementCount属性
  Element Traversal规范定义了ElementTraversal接口,它允许脚本遍历DOM树中的元素(element)节点,而不包含元素节点之外的其他节点,如注释节点、文字节点等。这个规范给我们提供了快速、方便的方法来访问元素节点。在以前的方法中,我们使用firstChild、nextSibling、childNodes、childrem等方法来进行遍历,但要得到元素节点,我们还需要来判断节点的类型。

注意:children属性中,IE里面包含注释节点,而其他浏览器则不包含。

ElementTraversal接口定义了5个属性,是元素节点必须要实现的,这5个属性的原始定义如下,这些属性,看名字就不难明白它的含义:

firstElementChild:Returns the first child element node of this element. null if this element has no child elements.
lastElementChild:Returns the last child element node of this element. null if this element has no child elements.
previousElementSibling:Returns the previous sibling element node of this element. null if this element has no element sibling nodes that come before this one in the document tree.
nextElementSibling:Returns the next sibling element node of this element. null if this element has no element sibling nodes that come after this one in the document tree.
childElementCount:Returns the current number of element nodes that are children of this element. 0 if this element has no child nodes that are of nodeType 1.

现在,IE9,Firefox3.5+,Safari,Opera,Chrome浏览器都已经实现该接口。

firstChild、nextSibling、childNodes、childrem等方法会获取文本节点、元素节点和注释节点以及空白节点。而firstElementChild、lastElementChild、previousElementSibling、nextElementSibling、childElementCount属性只获取元素节点。

例子:

<div id="test-div">
<div class="c-red">
    <p id="test-p">JavaScript</p>
    <p>Java</p>
  </div>
  <div class="c-red c-green">
    <p>Python</p>
    <p>Ruby</p>
    <p>Swift</p>
  </div>
  <div class="c-green">
    <p>Scheme</p>
    <p>Haskell</p>
  </div>
</div>

var haskell1 = document.getElementById('test-div').lastChild.lastChild;
var haskell2 = document.getElementById('test-div').lastElementChild.lastElementChild;

console.log(haskell1);//返回undefined;
console.log(haskell2);//返回  <p>Haskell</p>;

原因是有空白节点,如果把HTML所有标签写在一行,那么console.log(haskell1);也可返回<p>Haskell</p>;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容