JavaScript – Get Children of an HTML Element
To get the children of a specific HTML Element using JavaScript, get reference to this HTML element, and read the children
property of this HTML Element.
children
property returns HTMLCollection
object which contains the child elements in this HTML Element.
In the following example, we will get the children elements of the HTML Element which is selected by id "myElement"
.
example.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Get Children of this HTML Element using JavaScript</h2>
<div id="myElement">
<p>Hello <span>World</span>!</p>
<ul><li>List Item</li></ul>
<div>Sample World</div>
</div>
<br>
<button type="button" onclick="execute()">Click Me</button>
<p id="out"></p>
<script>
function execute(){
var element = document.getElementById('myElement');
var children = element.children;
document.getElementById('out').innerHTML = children.length + " children of #myElement.";
}
</script>
</body>
</html>
We can access each of the child in element.children
using index, as shown in the following example.
example.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Get Children of this HTML Element using JavaScript</h2>
<div id="myElement">
<p>Hello <span>World</span>!</p>
<ul><li>List Item</li></ul>
<div>Sample World</div>
</div>
<br>
<button type="button" onclick="execute()">Click Me</button>
<p id="out"></p>
<script>
function execute(){
var element = document.getElementById('myElement');
var children = element.children;
console.log(children[0]);
console.log(children[1]);
console.log(children[2]);
}
</script>
</body>
</html>
Try this html file online, and click on the Click Me
button. Children of the element with id myElement
are accessed using index and printed to the console output as shown in the following screenshot.
Conclusion
In this JavaScript Tutorial, we learned how to get the number of child elements of an HTML Element using JavaScript.