Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

childNodes - whitespace inside elements

<div id="myDIV">
<p>First p element (index 1)</p>
<p>Second p element (index 3)</p>
</div>

Trying to understand why index 0 is a text node.

According to this example from w3schools, index 0, 2, & 4 are text nodes. Index 1 & 3 are p elements.

Is index 0 a text node because it is whitespace? If so, where does this whitespace exist? Between the opening div tag and first opening p tag?

like image 798
wallwalker Avatar asked Oct 14 '25 08:10

wallwalker


1 Answers

Line breaks are whitespace, too. If you put those elements on a single line, you can omit whitespaces.

<div id="myDIV"><p>First p element (index 0)</p><p>Second p element (index 1)</p></div>

EDIT

The index numbers in the question, as well as in my answer, are node indices. One can use them EG. using the childNodes property.

On the other hand, one can use element indices, that do not count text and comment nodes, EG by accessing the childern property.

like image 68
Usagi Miyamoto Avatar answered Oct 16 '25 22:10

Usagi Miyamoto