user12097954
user12097954

Reputation:

How do I get all child text from a div and separate with a space?

Say I have this:

<div id ="element">
    <span>Hey</span>
    <div>
         <span>What up?</spa>
    </div>
    Yeah more text here.
</div>

How can I get all of the text in the note and it's descendants in a single text line with a space between each new child? I am looking for.

'Hey What up? Yeah more text here.'

I tried:

var text = document.getElementById("element").textContent;

But that makes all the words bunched up like.

'HeyWhat up?Yeah more text here.'

Note the amount of child elements is dynamic and it might just be 5 or 100.

Upvotes: 2

Views: 1523

Answers (2)

Unmitigated
Unmitigated

Reputation: 89374

You can loop over all the child nodes recursively to find text nodes.

const div = document.querySelector("#element");
const text = [];
div.childNodes.forEach(function check(child){
  if(child.nodeType === Node.TEXT_NODE){
    text.push(child.nodeValue.trim());
  }
  child.childNodes.forEach(check);
});
console.log(text.join(' '));
<div id ="element">
    <span>Hey</span>
    <div>
         <span>What up?</span>
    </div>
    Yeah more text here.
</div>

Upvotes: 3

Kharel
Kharel

Reputation: 837

const text = document.querySelector("#element").textContent.replace(/\s+/g, " ").trim();

console.log(text);
<div id="element">
  <span>Hey</span>
  <div>
    <span>What up?</spa>
  </div>
  Yeah more text here.
  This is <u>Nice</u>
  
  <i>One</i>
  <div>
    <p><b>!</b></p>
  </div>
</div>

Upvotes: 2

Related Questions