- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
HTML DOM children Property
The HTML DOM children property is used to return all the child elements of the specified element in the form of HTML collection. It is only a read-only property. The elements obtained can then be accessed by using index numbers which starts from 0.
The elements appear in the same order as they are in the HTML document. It contains only children nodes and doesn’t include whitespace and comments like childNodes property.
Syntax
Following is the syntax for the children property −
element.children
Let us see an example of the HTML DOM children property −
<!DOCTYPE html> <html> <head> <style> div { border: 1px solid blue; margin: 7px; } </style> </head> <body> <p>Click the button below to find out the number of div element children</p> <button onclick="myChild()">COUNT</button> <div id="DIV1"> <p>First p element </p> <p>Second p element </p> </div> <p id="Sample"></p> <script> function myChild() { var x = document.getElementById("DIV1").children.length; document.getElementById("Sample").innerHTML = "The div element has "+x+" child nodes"; } </script> </body> </html>
Output
This will produce the following output −
On clicking COUNT button −
In the above example −
We have created a
div { border: 1px solid blue; margin: 7px; } <div id="DIV1"> <p>First p element </p> <p>Second p element</p> </div>
We have then created a COUNT button which will execute myChild() function when clicked by the user −
<button onclick="myChild()">COUNT</button>
The myChild() function gets the element which has id equals “DIV1” which in our case is the <div> element and gets its children.length property value and assigns it to the variable x. Important thing here is the children property does not consider whitespace and comments so it will only consider the two <p> elements and the children.length will return 2. This value is then displayed in the paragraph with id “Sample” using the innerHTML() method −
function myChild() { var x = document.getElementById("DIV1").children.length; document.getElementById("Sample").innerHTML = "The div element has "+x+" child nodes"; }