What is a child node in javascript?

I was wondering, JavaScript offers a variety of methods to get the first child element from any element, but which is the best? By best, I mean: most cross-browser compatible, fastest, most comprehensive and predictable when it comes to behaviour. A list of methods/properties I use as aliases:

var elem = document.getElementById('container');
var child = elem.children[0];
var child = elem.firstElementChild; // == children[0]

This works for both cases:

var child = elem.childNodes[0]; // or childNodes[1], see below

That’s in case of forms, or <div> iteration. If I might encounter text elements:

var child = elem.childNodes; // treat as NodeList
var child = elem.firstChild;

As far as I can work out, firstChild uses the NodeList from childNodes, and firstElementChild uses children. I’m basing this assumption on the MDN reference:

childNode is a reference to the first child element of the element node, or null if there isn’t one.

I’m guessing that, in terms of speed, the difference, if any, will be next to nothing, since firstElementChild is effectively a reference to children[0], and the children object is already in memory anyway.

What does throw me, is the childNodes object. I’ve used it to take a look at a form, in a table element. While children lists all form elements, childNodes also seems to include whitespace from the HTML code:

console.log(elem.childNodes[0]);
console.log(elem.firstChild);

Both log <TextNode textContent="\n ">

console.log(elem.childNodes[1]);
console.log(elem.children[0]);
console.log(elem.firstElementChild);

All log <input type="text">. How come? I’d understand that one object would allow me to work with the “raw” HTML code, while the other sticks to the DOM, but the childNodes element seems to work on both levels.

To get back to my initial question, my guess would be: if I want the most comprehensive object, childNodes is the way to go, but because of its comprehensiveness, it might not be the most predictable in terms of it returning the element I want/expect at any given moment. Cross-browser support might also prove to be a challenge in that case, though I could be wrong.

Could anyone clarify the distinction between the objects at hand? If there is a speed difference, however negligible, I’d like to know, too. If I’m seeing this all wrong, feel free to educate me.


PS: Please, please, I like JavaScript, so yes, I want to deal with this sort of thing. Answers like “jQuery deals with this for you” are not what I’m looking for, hence no jquery tag.

To get all child nodes of an element, you can use the childNodes property. This property returns a collection of a node's child nodes, as a NodeList object.

By default, the nodes in the collection are sorted by their appearance in the source code. You can use a numerical index (start from 0) to access individual nodes.

Let us say you have the following HTML code:

<ul id="langs">
    <li>JavaScript</li>
    <li>Node</li>
    <li>Java</li>
    <li>Ruby</li>
    <li>Rust</li>
</ul>

The following example selects all child nodes of the <ul> tag and print their content:

const ul = document.querySelector('#langs');

// get all children
const childern = ul.childNodes;

// iterate over all child nodes
childern.forEach(li => {
    console.log(li.innerText);
});

Here is how the output looks like:

undefined
JavaScript
undefined
Node
undefined
Java
undefined
Ruby
undefined
Rust
undefined

Wait, why undefined appears in the output?

This is because whitespace inside elements is considered as text, and text is treated as nodes. It also applies to comments that are considered as nodes too.

If you want to exclude comment and text nodes, use the children property instead. This property returns a collection of a node's element nodes only, as an HTMLCollection object:

const children = ul.children;

// iterate over all child nodes
Array.from(children).forEach(li => {
    console.log(li.innerText);
});

Here is how the output looks like now:

JavaScript
Node
Java
Ruby
Rust

The difference between childNodes and children is that childNodes returns a NodeList object containing all nodes, including text nodes and comment nodes, while children returns an HTMLCollection object only containing element nodes.

To get the first and last children of an element, JavaScript provides firstChild and lastChild properties:

const ul = document.querySelector('#langs');

// get first children
const firstChild = ul.firstChild;

// get last children
const lastChild = ul.lastChild;

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

What is a 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. Nodes higher than a given node in the same lineage are ancestors and those below it are descendants.

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.

How do you get a child of node JS?

To get the first child element of a specified element, you use the firstChild property of the element:.
let firstChild = parentElement.firstChild; ... .
let content = document.getElementById('menu'); let firstChild = content.firstChild.nodeName; console.log(firstChild); ... .
#text..

What is Javascript child method?

The children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.