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?
I have found myself using JavaScript and I ran across childNodes and children properties.
Share
Understand that
.childrenis a property of an Element. 1 Only Elements have.children, and these children are all of type Element. 2However,
.childNodesis a property of Node..childNodescan contain any node. 3A concrete example would be:
Most of the time, you want to use
.childrenbecause 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
.textContentor.nodeValueinstead. 4It’s important to understand the distinction between the 2, before deciding which one to use: The
.textContentproperty represents the text content of the node and its descendants whereas the.nodeValueproperty represents the value of the current node.1. Technically, it is an attribute of ParentNode, a mixin included by Element.
2. They are all elements because
.childrenis a HTMLCollection, which can only contain elements.3. Similarly,
.childNodescan hold any node because it is a NodeList.4. Or
.innerText. See the differences here or here.