4

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?

asv
  • 3,332
  • 7
  • 24
  • 47

1 Answers1

4

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • If I have a node element (finded with 'childNodes[i].nodeType == 3'), how can I have a reference to the element? If I write console.log(childNodes[i]) I have – asv Dec 14 '17 at 19:00
  • @asv That should not happen, a comment node has `nodeType` 8. Can you make a [mcve] that demonstrates this problem? – Bergi Dec 14 '17 at 19:03