怎样遍历所有同级节点

var el = document.getElementById('div1').firstChild;

while (el !== null) {
  console.log(el.nodeName);
  el = el.nextSibling;
}

原理: 使用了 Node.prototype.nextSibling 在获取不到后面的同级节点时返回 null 的这个特性.

 

另一个方法是使用 Node.prototype.childNodes.

posted on 2019-09-11 14:00  aisowe  阅读(435)  评论(0编辑  收藏  举报

导航