Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Node.firstChild — the first child node

Node.firstChild is a read-only property that returns the first direct child node or null. It includes text and comments, so the returned node is not necessarily an element.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

node.firstChild

Node.firstChild reads the first direct child node in tree order, not the first element at any depth. It returns a Node object, or null if the node has no children. It is a read-only property, not a method: use node.firstChild, without call parentheses.

A child can be an element, a Text node, or a Comment node. Text containing only whitespace counts too. If you need the first child that is an element, use firstElementChild on an Element, Document, or DocumentFragment; that property skips text and comments.

Check for null before accessing properties of the result. Reading does not create a copy: you can modify the returned node. After children are added or removed, another read of firstChild reflects the current tree; a previously saved reference does not switch to the new first child.

The example creates a detached element, adds whitespace text and an element, and then removes the children. It requires a browser DOM environment. This is a DOM-standard API, not a feature of a particular ECMAScript edition; the Node.js version in a repository does not establish browser API support.

Examples

const parent = document.createElement('div');
const text = document.createTextNode('\n  ');
const element = document.createElement('span');
parent.append(text, element);

console.log(parent.firstChild === text);
console.log(parent.firstChild.nodeType === Node.TEXT_NODE);
console.log(parent.firstElementChild === element);
parent.removeChild(text);
console.log(parent.firstChild === element);
parent.removeChild(element);
console.log(parent.firstChild === null);

Result

true
true
true
true
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources