+ 1

Please who can explain why the alert output is 5 and not 2?

https://code.sololearn.com/Wsf1Zfv8ZJU6/?ref=app

1st Jul 2017, 6:55 PM
Chris Cypher
Chris Cypher - avatar
6 ответов
+ 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.
1st Jul 2017, 7:16 PM
Maz
Maz - avatar
+ 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...
1st Jul 2017, 7:24 PM
Rory Gaddin
Rory Gaddin - avatar
+ 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.
1st Jul 2017, 7:06 PM
Chris Cypher
Chris Cypher - avatar
+ 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.
1st Jul 2017, 7:21 PM
Chris Cypher
Chris Cypher - avatar
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
1st Jul 2017, 7:19 PM
Rory Gaddin
Rory Gaddin - avatar
0
@Christian sorry my mistake
1st Jul 2017, 7:42 PM
Manual
Manual - avatar