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 child elements are sorted in the order they appear in the element. Use the length
property of the HTMLCollection object to get the number of child elements, and then access each child element using its index (starting from 0).
The difference between the children
property and the childNodes
property:
- The
childNodes
property returns all nodes, including text nodes and comment nodes. - The
children
property returns only element nodes.
Browser Support
Property | |||||
---|---|---|---|---|---|
children | 2.0 | 9.0* | 3.5 | 4.0 | 10.0 |
Note: IE6 to IE8 fully support the children
property, but they return element nodes and comment nodes. IE9 and above return only element nodes.
Syntax
element.children
Technical Details
Return Value: | HTMLCollection object, representing a collection of element nodes, sorted in the order they appear in the source code. |
---|---|
DOM Version | DOM 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[1].style.backgroundColor = "yellow";
Example
Get the text of the third (index 2) child element of a select element:
var c = document.getElementById("mySelect").children;
document.getElementById("demo").innerHTML = c[2].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[i].style.backgroundColor = "red";
}