Get All The Child DIV IDs Inside a DIV Using jQuery .map() Function - jQuery get Child Elements by ID

Sometimes we need to find child element id’s inside another element. Traditionally, a “DIV” is used as a container and there can be other DIV elements inside it. You can place these elements during the designing of the web page or create and insert in it dynamically.
<div id="Container">
    <div id="Div1"></div>
    <div id="Div2"></div>
</div>

In the above example, I have added two DIV elements inside a DIV element. The element with the id Container serves as the parent element. Our objective is to extract the ids of the two child DIV, knowing that the ids (once extracted) will help us manipulate values at runtime. jQuery .map() function has made the execution very simple. In addition, all this we can do using very few lines of codes.

You may also like: How to get IDs of DIV element inside a DIV using plain JavaScript

The jQuery .map() function is an iterator and can be used to get or set values of the elements. Since it iterates or loops through elements, it returns an array of elements and that is what we need.

$('#Container > div').map(function() {
    console.log(this.id);
});
Here's an example

Also Read: How to append duplicate elements and contents using jQuery .clone() Method

<!DOCTYPE html>
<html>
<head>
    <title>Get All The Child DIV IDs Inside a DIV Using jQuery</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
    <!--The parent and child elements.-->
    <div id="Container">
        Inside parent DIV

        <div id="Div1">Child DIV 1</div>
        <div id="Div2">Child DIV 2</div>
    </div>
        
    <h3>Result</h3>
    <div id="showChild"></div>  <!--Display the result.-->
</body>

<script>
    $(document).ready(function() {
        // Count number of child DIVs.
        $('#showChild').append('Found <b>' + $('#Container > div').length + 
            '</b> child DIV elements <br />');

        // Show the child DIVs using .map function.
        $('#Container > div').map(function() {
            $('#showChild').append(this.id + '<br />');
        });
    });
</script>
</html>
Try it

Also Read: Disable or Enable Submit Button using jQuery .prop() Method

Conclusion

Although the jQuery .map() function gets all the id’s from inside the parent container, we are in fact using JQuery length property to get the total count of child DIV id’s. The total figure gives us an idea about the number child DIV elements inside a container and can help us analyze and execute other procedures.

$('#Container > div').length;

Previous - A Simple Accordion Menu using jQuery and CSSNext - 3 ways to find the File Extension using JavaScript and jQuery



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Google+

Related Posts: