Tristan Tran
Tristan Tran

Reputation: 1513

Extract and combine all text child nodes

Suppose I have a node list created by appending text child nodes dynamically as following:

const container = document.getElementById('container')
for (var i = 0;i < 5;i++) {
  let containerChild = document.createTextNode('a')
   container.appendChild(containerChild)
}    
<div id="container"></div>

Assuming that only text nodes are appended, what is the fastest / most clean way to extract the full text? In the case above, I am looking to get the string aaaaa. Of course I can loop through the parent node container to extract each child and then combine them. Just wondering if there is a better way. Thanks.

Upvotes: 0

Views: 816

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370979

The .textContent of the parent will combine them automatically:

const container = document.getElementById('container')
for (var i = 0;i < 5;i++) {
  let containerChild = document.createTextNode('a')
   container.appendChild(containerChild)
}

const text = container.textContent;
console.log(text, text.length);
<div id="container"></div>

(.innerHTML works too)

Upvotes: 1

Related Questions