children和 childNodes辨析

children和 childNodes辨析

相同点
  1. 只读属性
  2. 返回一个HTMLCollection集合
不同点
children
  • 返回所有节点,包含文本节点,注释等节点
let children = parentNode.children
for(let i = 0; i < children.length; i++) {
  // 只要元素节点
  if (children.nodeType === 1) {
    // do something
  }
}
childNodes

返回的是元素节点

总结

最大区别是 children会返回文本节点,而childNodes只返回元素节点

posted @ 2021-02-17 12:15  HelloCoderRookie  阅读(91)  评论(0编辑  收藏  举报