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

258
Visualizações
JS - how to get text content from a node as it is displayed on the page

Small reproducible code:

<div id="box">
    abc 
    <b>def</b>
    <p>ghi</p>
    jk
    lm
    <div style="color: green;">
        nop
    </div>
</div>

<script>
    let boxElement = document.getElementById("box");
    
    let processChildNode = function(htmlElement)
    {
        let childNode = htmlElement.firstChild;
        while (childNode) 
        {
            switch(childNode.nodeType)
            {
                case Node.ELEMENT_NODE:
                    processChildNode(childNode);
                    break;
                case Node.TEXT_NODE:
                    let plainText = childNode.nodeValue;
                    console.log(plainText);
                    break;
            }
            
            // Gets next node
            childNode = childNode.nextSibling;
        }
    };

    processChildNode(boxElement);
</script>

Result on the rendered page in the browser:

Rendered page

Result in the debug console:

innerText.html:27 
        abc 
        
innerText.html:27 def
innerText.html:27 
        
innerText.html:27 ghi
innerText.html:27 
        jk
        lm
        
innerText.html:27 
            nop
        
innerText.html:27 

Issue is most apparent in the case of "jk" and "lm". There is a new line between them in the debug console, not in the rendered page...

I noticed "innerText" can do it for me but this variable is not available in node element. How can I fix that?

ps.

For me it is important to process the node separately. I can't do that:

console.log(boxElement.innerText)
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As far as I can see, there is no native method to solve this problem. If your concern is just about getting rid of the white space you could do this:

switch(childNode.nodeType){
    case Node.ELEMENT_NODE:
        processChildNode(childNode);
        break;
    case Node.TEXT_NODE:
        let plainText = childNode.nodeValue.replace(/\s+/gs, " ").trim();
        console.log(plainText);
        break;
}
about 4 years ago · Juan Pablo Isaza 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