Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery, retrieve children and grandchildren

Let's say I have a JQuery object which has (or points to) such a structure:

<div id="parent">
  <div id="child1">
    <div id="grandchild1">
      // ... grandchild can also have children
    </div>
    // ... and so on of grandchildren
  </div>
  <div id="child2">

  </div>
  // .... and so on
</div>

Is there possibility to get plain array of elements (JQuery object) from my object like this:

['parent', 'child1', 'child2', ..., 'grandchild1', ...]

Thanks

P.S. Please notice that it can't be selector something like this $('div > div'), because I already have JQuery object and only from this object I need take stuff.

like image 765
megas Avatar asked Jul 05 '11 11:07

megas


1 Answers

You can retrieve children and grandchildren using the * selector. The items will be returned in tree order. You can then get a plain array of elements using jQuery.toArray():

$(function() {
  var a = $("#wrapper").find("*").toArray();
  console.log(a);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div id="wrapper">
  <div id="parent">
    <div id="child1">
      <div id="grandchild1">
        <div class="level-4"></div>
        <div class="level-4"></div>
        <div class="level-4"></div>
      </div>
    </div>
    <div id="child2">
      <div class="level-3"></div>
      <div class="level-3"></div>
      <div class="level-3"></div>
      <div class="level-3">
        <div class="level-4"></div>
        <div class="level-4"></div>
        <div class="level-4"></div>
      </div>
    </div>
  </div>
</div>

Following is an overkill but useful if you are more interested in iterating the hierarchy using recursion:

function recursiveIterate($node, array) {
  $node.children().each(function() {
    array.push(this);
    recursiveIterate($(this), array);
  });
}
$(function() {
  var a = [];
  recursiveIterate($("#wrapper"), a);
  console.log(a);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div id="wrapper">
  <div id="parent">
    <div id="child1">
      <div id="grandchild1">
        <div class="level-4"></div>
        <div class="level-4"></div>
        <div class="level-4"></div>
      </div>
    </div>
    <div id="child2">
      <div class="level-3"></div>
      <div class="level-3"></div>
      <div class="level-3"></div>
      <div class="level-3">
        <div class="level-4"></div>
        <div class="level-4"></div>
        <div class="level-4"></div>
      </div>
    </div>
  </div>
</div>
like image 146
Salman A Avatar answered Oct 19 '22 07:10

Salman A