How to get the list of divs inside another div in JQuery?

2.6k Views Asked by At

Following is my html code.

<div class="panels" id="panels">
   <div class = 'panel' id = 'panel1' title = 'Learners Status' ></div>
   <div class = 'panel' id = 'panel2' title = 'ILR Status' ></div>
   <div class = 'panel' id = 'panel3' title = 'Test Graph' ></div>
</div>

I want to get all panel divs inside the 'panels' div.

Following code is not working for me.

var children = $("div.panels").children('div');
alert(children.length);
2

There are 2 best solutions below

1
PeterKA On

It may be that your code is not at the bottom of the page, in which case you have to explicitly require the code to wait for DOM ready event:

$(function() {
    var children = $("div.panels").children('div.panel');
    alert(children.length);
});

$(function() {
  var children = $('div.panels').children('div.panel');
  children.each(function() {
    $('pre.out').append( 'id: ' + this.id + ', title: ' + this.title + '<br>' );
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="panels" id="panels">
   <div class = 'panel' id = 'panel1' title = 'Learners Status' ></div>
   <div class = 'panel' id = 'panel2' title = 'ILR Status' ></div>
   <div class = 'panel' id = 'panel3' title = 'Test Graph' ></div>
</div>


<h1>Children Details</h1>
<pre class="out"></pre>

2
Anwar On

  function displayPanelsTitles() {
      var mainPanel = document.getElementById("panels").childNodes;
      
      alert("Panel 1 : " + mainPanel[1].title + " Panel 2 : " + mainPanel[3].title + " Panel 5 : " + mainPanel[5].title);
    }
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset = "utf-8" />
        <title> test </title>
      </head>
      <body onload = "displayPanelsTitles()">
       <div class="panels" id="panels">
         <div class = 'panel' id = 'panel1' title = 'Learners Status' ></div>
         <div class = 'panel' id = 'panel2' title = 'ILR Status' ></div>
         <div class = 'panel' id = 'panel3' title = 'Test Graph' ></div>
        </div>
      </body>
    </html>

This one extract each div title. Hope it helps !