Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between children and childNodes in JavaScript?

Tags:

javascript

dom

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?

like image 768
John Avatar asked Oct 28 '11 22:10

John


People also ask

What is Javascript childNodes?

Child nodes include elements, text and comments. Note: The NodeList being live means that its content is changed each time new children are added or removed. The items in the collection of nodes are objects, not strings. To get data from node objects, use their properties.

What is the difference between a parent node and child node?

Any subnode of a given node is called a child node, and the given node, in turn, is the child's parent. Sibling nodes are nodes on the same hierarchical level under the same parent node.

What is parent node and child node in Javascript?

In the HTML DOM (Document Object Model), an HTML document is a collection of nodes with (or without) child nodes. Nodes are element nodes, text nodes, and comment nodes. Whitespace between elements are also text nodes. Elements are only element nodes.


2 Answers

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.

like image 159
Raynos Avatar answered Oct 13 '22 07:10

Raynos


Element.children returns only element children, while Node.childNodes returns all node children. Note that elements are nodes, so both are available on elements.

I believe childNodes is more reliable. For example, MDC (linked above) notes that IE only got children right in IE 9. childNodes provides less room for error by browser implementors.

like image 34
Matthew Flaschen Avatar answered Oct 13 '22 06:10

Matthew Flaschen