Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

300
Views
How to replace all blank space with &nbsp while ignoring html tags

I was replacing all of the spaces in a div element with   so I could easily read all the spaces with a JavaScript file. When I was coding this I realized the elements inside the div would get messed up because properties like ids requires spaces between the tag name and the property would get replaced breaking the tag. How could I ignore the space in between the tag and the name and only replace the text spaces.

Code:

let el = document.getElementById('parent');

function replaceText() {
  let text = el.innerHTML.split(' ').join(' ');
  el.innerHTML = text;
  console.log(text);
}
//I dont want the span tag or em tag to get messed up by this
<!DOCTYPE html>
<html>
  <body>
    <div id='parent'>
      Lorem ipsum 
      <span id='element'>
        <em id='child'>dolor sit amet</em>
      </span>
    </div>
    <button onclick='replaceText()'>Change with nbsp</button>
   </body>
</html>

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

The best way that I can think of is to look for text nodes in the element. You'll need to call the function recursively until there are no more text nodes. Here is some example code to get you started.

function replaceText(element) {
    for (let childNode of element.childNodes) {
        if (childNode.nodeType === Node.TEXT_NODE) {
            childNode.data = ' ' +  childNode.data.trim().replace(/ /g, '\u00a0') + ' '
            continue
        }

        // Recursively replace text for child node
        replaceText(childNode)
    }
}
<!DOCTYPE html>
<html>
  <body>
    <div id='parent'>
      Lorem ipsum 
      <span id='element'>
        <em id='child'>dolor sit amet</em>
      </span>
    </div>
    <button onclick='replaceText(document.getElementById("parent"))'>Change with nbsp</button>
   </body>
</html>

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!