+ 1
Please who can explain why the alert output is 5 and not 2?
6 Respostas
+ 9
Because whitespaces are considered as text and text is considered as node... in fact if you remove the whitespaces you will have just the two paragraph elements and the output will be two:
<div class="demo" id="demo2"><p>To illustrate this, let's go back to the car example </p><p>We instantiate our car by using a constructor method to create it.</p></div>
In your example you have three whitespaces (break lines) plus two paragraphs, so... five in total.
+ 2
A simpler answer than my previous one is just to change par.childNodes to par.children
The children property of a DOM node only includes other tags.
See https://www.w3schools.com/jsref/prop_element_children.asp for more...
+ 1
@manual, I don't think that's right. I didn't ask it to alert the string length of the id=demo2. Please check the code again.
Even if I change the ID to a longer string, the alert output for chd.length will still be 5.
+ 1
@Maz
You are right! Perfect!
Thanks a lot! I didn't consider the whitespaces. I thought HTML and JS weren't too concerned with whitespaces.
0
The carriage-return and tabs between your opening <div> tag and the first <p> tag are also considered a child of the <div> tag. Specifically, they are a TextNode. If you want to ignore these, then you'll need to strip them out from the NodeList returned by getElementById.
See https://code.sololearn.com/WxxVmGiaeTbX/ for a possible solution. The chd variable is now an Array at the end of the code listing, not a NodeList any longer, so this may or may not be what you want, depending on what else you're doing with the list of nodes further down the line.
HTH
0
@Christian
sorry my mistake