Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

330
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!