遍历文本节点和元素节点

Iterate through text node and element node

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

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,它同时包含元素和文本节点:

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