Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  102] [ 7]  / answers: 1 / hits: 137380  / 13 Years ago, fri, october 28, 2011, 12:00:00

I have found myself using JavaScript and I ran across childNodes and children properties. I am wondering what the difference between them is. Also is one preferred to the other?


More From » dom

 Answers
28

Understand that .children is a property of an Element. 1 Only Elements have .children, and these children are all of type Element. 2



However, .childNodes is a property of Node. .childNodes can contain any node. 3



A concrete example would be:



let el = document.createElement(div);
el.textContent = foo;

el.childNodes.length === 1; // Contains a Text node child.
el.children.length === 0; // No Element children.


Most of the time, you want to use .children because generally you don't want to loop over Text or Comment nodes in your DOM manipulation.



If you do want to manipulate Text nodes, you probably want .textContent instead. 4






1. Technically, it is an attribute of ParentNode, a mixin included by Element.

2. They are all elements because .children is a HTMLCollection, which can only contain elements.

3. Similarly, .childNodes can hold any node because it is a NodeList.

4. Or .innerText. See the differences here or here.


[#89387] Thursday, October 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aleighabayleef

Total Points: 511
Total Questions: 99
Total Answers: 99

Location: Aruba
Member since Fri, Jun 24, 2022
2 Years ago
;