Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 319
asv Avatar asked Oct 26 '25 14:10

asv


1 Answers

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.

like image 181
Bergi Avatar answered Oct 29 '25 07:10

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!