JavaScript – How to Get child elements inside a DIV

The post shows you how to get all child elements inside a DIV element. Here is the code how it works:

dom-example.js
function getChildElements(divId, childTagName) {
    var childElements = [];

    var container = document.getElementById(divId);
    if (container) {
        var allElements = container.childNodes;
        for (var i = 0; i < allElements.length; i++) {
            if (allElements[i].nodeName.toLowerCase() === childTagName.toLowerCase()) {
                childElements.push(allElements[i]);
            }	
        }
    }
    
    return childElements;
} 

Here is the example how to use the function:

example.html
<html>
<head>
    <title>How to Get child elements inside a DIV | ByteNota.com</title>
</head>
<body>

    <div id="message">
        <h2>What is Lorem Ipsum?</h2>

        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry</p>
        <p>Lorem Ipsum has been the industry's standard dummy text ever since the 1500s...</p>
    </div>

    <script type="text/javascript">

        function getChildElements(divId, childTagName) {
            var childElements = [];

            var container = document.getElementById(divId);
            if (container) {
                var allElements = container.childNodes;
                for (var i = 0; i < allElements.length; i++) {
                    if (allElements[i].nodeName.toLowerCase() === childTagName.toLowerCase()) {
                        childElements.push(allElements[i]);
                    }	
                }
            }

            return childElements;
        } 

        // get all p elements inside #message element
        var results = getChildElements('message', 'p');
        console.log(results);
    </script>

</body>
</html>

In the above code, we get all p elements inside div element having id is message. Finally, we print out the result to console.

0 0 vote
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x