The children property returns a live HTMLCollection of all child elements of a specified element, accessible by index. Unlike childNodes (which includes text and comment nodes), it contains only element nodes and is read-only.
Syntax
element.childrenReturn Value: It returns a collection of element nodes that can be accessed by indexing.
Example : In this example, we will use DOM children property
<!--Driver Code Starts-->
<!DOCTYPE html>
<html>
<head>
<title>
HTML DOM children Property
</title>
</head>
<body style="text-align:center">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h2>
DOM children Property
</h2>
<div id="parent">
<p>
A computer science portal for geeks.
</p>
<p>
Geeks classes an extensive programme for geeks.
</p>
</div>
<!--Driver Code Ends-->
<button onclick="Geeks()">Click me!</button>
<script>
function Geeks() {
let doc = document.getElementById("parent").children;
let i;
for (i = 0; i < doc.length; i++) {
doc[i].style.color = "white";
doc[i].style.backgroundColor = "green";
}
}
</script>
<!--Driver Code Starts-->
</body>
</html>
<!--Driver Code Ends-->
- Unlike childNodes (which includes text nodes, comments, etc.), element.children contains only element nodes. The collection is live, so it automatically updates when child elements are added or removed.
- Use children when you only care about element children. Use childNodes when you need every type of child node (including whitespace text nodes).