JavaScript – Iterate over Children of HTML Element

To iterate over Children of HTML Element in JavaScript, get the reference to this HTML Element, get children of this HTML using using children property, then use for loop to iterate over the children.

In the following example, we will get the children elements of the HTML Element which is selected by id "myElement", and iterate over the children using for loop. And for each child, we shall modify its font color.


<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    <h2>Iterave over Children of HTML Element using JavaScript</h2>
    <div id="myElement">
        <p>Hello <span>World</span>!</p>
        <ul><li>List Item</li></ul>
        <div>Sample World</div>
    <button type="button" onclick="execute()">Click Me</button>
    <p id="out"></p>
    function execute(){
        var element = document.getElementById('myElement');
        var children = element.children;
        for(var i=0; i<children.length; i++){
            var child = children[i];
   = "red";
Try Online


In this JavaScript Tutorial, we learned how to iterate over children of an HTML Element using JavaScript.