Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

301
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda