Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

257
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda