How to get text from an element with space in javascript

Viewed 474

The HTML code is pretty much like this

<div class="place" style="top: 4px;">
    <span class>text</span> 
    <span class>text</span>
    <span class>text</span>
</div>

For example with this code

let text = document.querySelector("div.place").textContent; //grab all text

I get all the text like this: thisisanexampletext
Is there a way to get text with spaces after each word?
like this: this is an example text

1 Answers

First you have to collect all the span elements. You then iterate through this collection and can read the text from each element with innerHTML / innerText. You push this into an array and at the end you can make the desired string out of it with the array function join().

let t = document.querySelectorAll("div.place span");

const text = [];
for(let i = 0; i < t.length; i++) {   
   text.push(t[i].innerHTML);
}

console.log(text.join(' '));
<div class="place" style="top: 4px;">
    <span class>text</span> 
    <span class>text</span>
    <span class>text</span>
</div>

Related