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.

example.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <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>
    </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;
        for(var i=0; i<children.length; i++){
            var child = children[i];
            child.style.color = "red";
        }
    }
    </script>
</body>
</html>

Conclusion

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