Get a collection of the <body> element's children:
const collection = document.body.children;
Try it Yourself »
More examples below.
The children
property returns a collection of an element's child elements.
The children
property returns an HTMLCollection object.
The firstElementChild Property
The nextElementSibling Property
The previousElementSibling Property
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.
childNodes returns child nodes (element nodes, text nodes, and comment nodes).
children returns child elements (not text and comment nodes).
Siblings are "brothers" and "sisters".
Siblings are nodes with the same parent (in the same childNodes list).
Element Siblings are elements with the same parent (in the same children list).
element.children
Type | Description |
Object | A HTMLCollection object. The collection of element nodes. The elements are sorted as they appear in the document. |
How many children does "myDIV" have:
let count = document.getElementById("myDIV").children.length;
Try it Yourself »
Change the background of the second child element of "myDIV":
const collection = document.getElementById("myDIV").children;
collection[1].style.backgroundColor = "yellow";
Try it Yourself »
Get the text of the third child element (index 2) of a <select> element:
const collection = document.getElementById("mySelect").children[2].text;
Try it Yourself »
Loop all children of <body> and change their background:
const collection = document.body.children;
for (let i = 0; i < collection.length; i++) {
collection[i].style.backgroundColor = "red";
}
Try it Yourself »
element.children
is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!