HTML DOM children Property
Example
Get the collection of child elements of the body element:
var c = document.body.children;
Definition and Usage
The children property returns a collection of an element's child elements, as an HTMLCollection object.
Note: The elements are sorted in the order they appear in the source code. Use the length property of the HTMLCollection object to get the number of child elements, then access each child element by its index (starting from 0).
The difference between the children property and the childNodes property:
- The
childNodesproperty returns all nodes, including text nodes and comment nodes. - The
childrenproperty returns only element nodes.
Browser Support
| Property | Chrome | Edge | Firefox | Safari | Opera |
|---|---|---|---|---|---|
| children | 2.0 | 9.0* | 3.5 | 4.0 | 10.0 |
* IE6 to IE8 fully support the children property, but it returns both element nodes and comment nodes. IE9 and later versions return only element nodes.
Syntax
element.children
Technical Details
| Return Value: | An HTMLCollection object, representing a collection of element nodes. The elements in the collection are in the same order as they are in the source code. |
|---|---|
| DOM Version: | DOM Level 1 |
More Examples
Example
Check how many child elements a div has:
var c = document.getElementById("myDIV").children.length;
Example
Change the background color of the second child element of a div:
var c = document.getElementById("myDIV").children;
c.style.backgroundColor = "yellow";
Example
Get the text of the third child element (index 2) in a select element:
var c = document.getElementById("mySelect").children;
document.getElementById("demo").innerHTML = c.text;
Example
Change the background color of all child elements of the body element:
var c = document.body.children;
var i;
for(i = 0; i<c.length; i++){
c.style.backgroundColor = "red";
}
YouTip