Search code examples
javascriptchildrennodechildren

Iterate through text node and element node


I used element.children to iterate through element nodes and childNodes for text node. How can I iterate both text node and element node?

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
  }
}

Can I access to an element with childNodes?


Solution

  • Just use childNodes, which contains both element and text nodes:

    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
      }
    }
    

    You should distinguish them by the nodeType, not by the nodeName.