Table of Contents

Getting child elements of a node in JavaScript is a common task when working with the Document Object Model (DOM). JavaScript provides properties such as children, childNodes, firstElementChild, and lastElementChild to access and navigate elements inside a parent node.

What Are Child Elements in JavaScript?

In the DOM tree, a child is a node directly nested inside another node. For example, an li element inside a ul element is a child element of that ul. A parent can contain element nodes, text nodes, and comment nodes. Child elements specifically refer to nested HTML elements.

<div id="parent">
  <h3>Fruits</h3>
  <ul>
    <li>Apple</li>
    <li>Banana</li>
    <li>Orange</li>
  </ul>
</div>

1. Using the children Property

The children property returns a live HTMLCollection containing only the element nodes directly inside a parent element. It does not include whitespace text nodes or comments.

const parent = document.getElementById("parent");
console.log(parent.children);
console.log(parent.children.length);

The collection contains the direct child elements. Its length property reports how many child elements the parent contains.

Access a Child Element by Index

Use bracket notation to access a child by its zero-based index. The first child element is at index 0.

console.log(parent.children[0]); // First child element
console.log(parent.children[1]); // Second child element
console.log(parent.children[2]); // Third child element

2. Using the childNodes Property

The childNodes property returns a live NodeList of all direct child nodes, including element nodes, text nodes, and comment nodes. Indentation and line breaks in HTML can create whitespace text nodes, so this collection may contain more entries than children.

const parent = document.getElementById("parent");
console.log(parent.childNodes);

parent.childNodes.forEach((node) => {
  console.log(node.nodeType, node.nodeName, node.textContent);
});

Use node.nodeType to identify a node: 1 represents an element, 3 a text node, and 8 a comment node.

3. Using firstElementChild and lastElementChild

If you only need the first or last child element, use firstElementChild or lastElementChild. Both return an element or null when no matching child exists.

const first = parent.firstElementChild;
const last = parent.lastElementChild;

console.log(first);
console.log(last);

4. Loop Through All Child Elements

Use a for...of loop to process every direct child element. The children HTMLCollection is iterable in modern browsers.

for (const child of parent.children) {
  console.log(child.tagName, child.textContent);
}

You can convert the collection into an array to use methods such as map() or filter().

const childArray = Array.from(parent.children);

childArray.forEach((child, index) => {
  console.log(index, child);
});

5. Select Child Elements with querySelectorAll()

The querySelectorAll() method selects descendants that match a CSS selector. Unlike children, it can find matching elements at any depth. To select only direct child elements, use the direct-child combinator (>) with :scope.

const allParagraphs = parent.querySelectorAll("p");
const directParagraphs = parent.querySelectorAll(":scope > p");

console.log(allParagraphs);
console.log(directParagraphs);

querySelectorAll() returns a static NodeList, so it does not automatically update when the DOM changes. The :scope selector refers to the element on which the query is performed.

children vs childNodes

Property Returns Includes text nodes? Collection type
children Direct child elements No HTMLCollection (live)
childNodes All direct child nodes Yes NodeList (live)

Common Mistakes

  • Confusing nodes with elements: childNodes includes whitespace text nodes, while children includes only elements.
  • Using the wrong index: Child collections use zero-based indexing, so the first item is [0].
  • Assuming a child always exists: Check the result before accessing its properties because firstElementChild can return null.
  • Expecting querySelectorAll() to be live: Its NodeList is static, unlike the live collection returned by children.

Practical Example: Display All Child Elements

You can combine the children property with a loop to read or update the direct child elements of a container. This example collects each child’s text and displays it in the browser console:

const list = document.getElementById("fruitList");

if (list) {
  for (const item of list.children) {
    console.log(item.textContent.trim());
  }
}

The if statement checks that the parent element exists before the code accesses its children. This is useful when a script runs on several pages that may not contain the same HTML structure. You can also add a class to each child element:

for (const item of list.children) {
  item.classList.add("list-item");
}

How to Check Whether a Parent Has Child Elements

Check the length property of children before trying to access an item. A value of zero means that the parent currently has no direct child elements.

if (list && list.children.length > 0) {
  console.log("The parent has child elements.");
} else {
  console.log("No child elements were found.");
}

Categorized in:

Javascript, Js DOM,