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

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

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 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