2

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

5
  • Show HTML, textContent would have worked... Commented Nov 24, 2021 at 13:07
  • Can you give us full example using code snippet please? Attribute textContent returns text content as it is - with whitespaces. Commented Nov 24, 2021 at 13:08
  • @decpk not if the text is divided in different childs and there's some css going on. Commented Nov 24, 2021 at 13:11
  • can you check if document.querySelector("div.place").innerText will do? Commented Nov 24, 2021 at 13:18
  • it still gives the same output with no spaces Commented Nov 24, 2021 at 13:52

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

It is also possible in this way..

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

for(let i = 0; i < t.length; i++) {   
   t[i].innerHTML += " ";
}
<div class="place" style="top: 4px;">
    <span class>text</span> 
    <span class>text</span>
    <span class>text</span>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.