<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.
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); });
<!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>
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;