Home > Net >  How to replace all blank space with   while ignoring html tags
How to replace all blank space with   while ignoring html tags

Time:04-14

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>

CodePudding user response:

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>

  • Related