nextSibling 和nextElementSibling

在使用DOM过程中发现一个问题:

使用nextSibling 属性返回指定节点之后紧跟的节点,在相同的树层级中。被返回的节点以 Node 对象返回。

this.arrow = this.screen.nextSibling;
this.left = this.arrow.children[0]; // undefined
this.right = this.arrow.children[1]; // undefined

// 使用nextElementSibling
this.arrow = this.screen.nextElementSibling;
this.left = this.arrow.children[0]; // 正常获取第一个子节点
this.right = this.arrow.children[1]; // 正常获取第2个子节点

nextSibling属性与nextElementSibling属性的差别:
nextSibling属性返回元素节点之后紧跟的兄弟节点(包括文本节点、注释节点即回车、换行、空格、文本等等);
nextElementSibling属性只返回元素节点之后紧跟的兄弟元素节点(不包括文本节点、注释节点);

注意: 空格、回车也会看作文本,以文本节点对待。

原文地址:https://www.cnblogs.com/codebook/p/10811970.html