HTML Element .children / firstElementChild / lastElementChild Since: DOM Level 1(1998)
Properties for retrieving child elements of an HTML element. You can get a list of child elements, or the first and last child element.
Syntax
// Get a list of child elements. var elements = element.children; // Get the first child element. var first = element.firstElementChild; // Get the last child element. var last = element.lastElementChild;
Property List
| Property | Description |
|---|---|
| children | Returns only HTML element children as an HTMLCollection. Text nodes and comment nodes are not included. |
| childNodes | Returns all child nodes, including text nodes and comment nodes, as a NodeList. |
| firstElementChild | Returns the first child element (HTML element). Returns null if no child elements exist. |
| lastElementChild | Returns the last child element (HTML element). Returns null if no child elements exist. |
| firstChild | Returns the first child node. Text nodes and comment nodes are included. |
| lastChild | Returns the last child node. Text nodes and comment nodes are included. |
Sample Code
<ul id="list"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul>
var list = document.querySelector("#list");
// Use children to get only HTML element children.
console.log(list.children.length); // Outputs: 3
console.log(list.children[0].textContent); // Outputs: "Item 1"
console.log(list.children[2].textContent); // Outputs: "Item 3"
// childNodes includes text nodes, so the count differs.
console.log(list.childNodes.length); // Outputs: 7 — whitespace between tags is counted as text nodes.
// Get the first and last child elements.
console.log(list.firstElementChild.textContent); // Outputs: "Item 1"
console.log(list.lastElementChild.textContent); // Outputs: "Item 3"
// firstChild may return a text node.
console.log(list.firstChild); // Returns a text node for the newline and whitespace.
Notes
element.children returns only HTML element children as an HTMLCollection. element.childNodes returns all child nodes, including text nodes and comment nodes, so for typical DOM manipulation, using element.children — which only includes HTML elements — helps avoid unexpected results.
In HTML source code, line breaks and indentation whitespace between tags are treated as text nodes. As a result, using childNodes, firstChild, or lastChild may return whitespace text nodes. When you need to reliably retrieve HTML elements only, use children, firstElementChild, or lastElementChild.
To count child elements, use children.length. If you need to find child elements matching a specific condition, element.querySelector() or element.querySelectorAll() are more convenient.
Browser Compatibility
2.5 or earlier ×
3.1 or earlier ×
5 or earlier ×
9 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.