【问题标题】:Iterate through text node and element node遍历文本节点和元素节点
【发布时间】:2017-12-11 17:03:49
【问题描述】:

我使用 element.children 遍历元素节点和文本节点的 childNodes。 如何迭代文本节点和元素节点?

let children = this.element.children;
for (let i = 0; i < children.length; i++) {
  // do something with children[i] element
}
let childrenNodes = this.element.childNodes;
for (let i = 0; i < childrenNodes.length; i++) {
  if (childrenNodes[i].nodeName == "#text") {
    // do something with childrenNodes[i] text node
  }
}

我可以使用 childNodes 访问元素吗?

【问题讨论】:

  • 请贴一些代码(当前的 HTML/JS 等)

标签: javascript children nodechildren


【解决方案1】:

只需使用childNodes,它同时包含元素和文本节点:

const childNodes = this.element.childNodes;
for (let i = 0; i < childNodes.length; i++) {
  if (childNodes[i].nodeType == 1) {
    // do something with childrenNodes[i] element
  } else if (childNodes[i].nodeType == 3) {
    // do something with childrenNodes[i] text node
  }
}

你应该用nodeType来区分它们,而不是nodeName

【讨论】:

  • 如果我有一个节点元素(使用 'childNodes[i].nodeType == 3' 找到),我如何才能引用该元素?如果我写 console.log(childNodes[i]) 我有
  • @asv 这不应该发生,评论节点有nodeType 8。你能做一个minimal reproducible example 来演示这个问题吗?
猜你喜欢
  • 2013-04-01
  • 1970-01-01
  • 2017-09-18
  • 2013-07-20
  • 2014-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多