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

329
Vistas
how does childNode indexing work with javascript?

For example, if I have

              <div>
                <h2>Name</h2>
                <h3>age</h3>
                <span class='fa fa-trash'></span>
             </div>

and when clicking the span (icon) I say

this.parentNode.childNodes[1].innerText

it would target the Name but if I say

this.parentNode.childNodes[2].innerText

it would not target Age. why is this? Is there a resource that explains this well? I know the indexing doesn't start at 0 but I don't understand how the indexing work.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

DOM is not just the elements you see in your HTML code. In-between each element is a "text node" where text can be displayed. An example of this would be having text in a div below a a header. So...

<div>
    <!-- Index 0: Text node -->
    <h1>Header Text</h1> <!-- Index 1: Element -->
    Description Text <!-- Index 2: Text node -->
</div>

As you can see, you are allowed to insert text in the div without wrapping it in an element. These are called text nodes which you see when you put the text in normal text elements (such as span or p) or buttons (<button>TEXT</button>). So to get around this in you JavaScript code, you could either do it the lazy way;

document.getElementById("ELEMENT_ID").childNodes[INDEX*2 + 1]

or by using the children property;

document.getElementById("ELEMENT_ID").children[INDEX]

The problem with this method is that it only returns 'element' children within the div, so the description text in the above HTML example will not be accessible. ([H1] instead of [Text, H1, Text]), but I suppose that is what you're looking for anyway. :)

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