Back

Technologies:

javascriptjavascript
htmlhtml
avatar
Tolerim
20 hours ago

Can there be an additional text node in a node list?

I need to extract all children of a section element containing 3 parent div elements and log them. The following code snippet demonstrates the HTML structure:

hello

bro

bro

To achieve this, I have used the following code:

const section = document.querySelector('.section1');
console.log(section.childNodes);
When executing the code, I noticed that the output generated was strange. It contained extra text in the NodeList. To understand the reason behind this, I tried logging section.children, which successfully returned the Element Nodes in an HTMLcollection. However, I need to know the reason behind the extra text in section.childNodes Node List. Can you please explain?
Answers(1)
avatar
Tolerim
20 hours ago
Verified Answer
The extra text in the section.childNodes node list are Text Nodes which represent the white space between the elements in the HTML code. In this case, they represent the line breaks and white spaces between the div elements. On the other hand, section.children only returns the element nodes and does not include the text nodes. Therefore, if you want to only log the element nodes inside a parent element, you should use the parentElement.children property instead of the parentElement.childNodes property. In your case, you can log only the element nodes within the section1 element by using the following code:
const section = document.querySelector('.section1');
console.log(section.children);
This will output a HTMLCollection of all the child elements within the section1 element, which in your case are the 3 div elements with class parent.
;