最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - JQuery, retrieve children and grandchildren - Stack Overflow

matteradmin16PV0评论

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.

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.

Share Improve this question edited Jan 28, 2018 at 15:22 Salman Arshad 272k84 gold badges442 silver badges533 bronze badges asked Jul 5, 2011 at 11:56 megasmegas 21.8k12 gold badges82 silver badges134 bronze badges 4
  • I'm curious to know what you mean by "...get plain array of elements (JQuery object)...". Which did you want? An Array, or a jQuery object? – user113716 Commented Jul 5, 2011 at 12:07
  • jQuery object is actually array, right? I meant that I want to get parent and all nested elements – megas Commented Jul 5, 2011 at 12:28
  • No, a jQuery object is sometimes called an Array-like object, but it isn't an actual Array. – user113716 Commented Jul 5, 2011 at 12:36
  • I'm new to jQuery so I can't be specific, I often treat jQuery object as an array. – megas Commented Jul 5, 2011 at 12:47
Add a comment  | 

3 Answers 3

Reset to default 18

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() {
  let a = $("#wrapper")
    .find("*")
    .addBack() // add the previous match i.e. #wrapper itself to the collection
    .toArray();
  console.log(a);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.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://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.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>

You can use the toArray()[docs] method to make your jQuery object into an Array.

var arr = my_obj.toArray();

...or the get()[docs] method if you don't pass it any arguments.

var arr = my_obj.get();

If I've misunderstood, and you're pointing to the root of the structure, and need to get its descendants, use the find()[docs] method method.

var descendants = my_obj.find('div');

jQuery has many traversal methods that let you get around the DOM structure from a given point.


If you only wanted children and grandchildren, and nothing deeper, do this:

var two_generations = my_obj.find('> div > div');

This will give you div elements only 2 generations deep.

If you don't want to limit it to div elements, do this:

var two_generations = my_obj.find('> * > *');

Hey man I'm pretty new here and I was having a similar brain fart. To get the grandchildren, I suggest using the .children() approach:

$('#parent') //selects the parents
$('#parent').children() //selects the children
$('#parent').children().children() //selects the grandchildren

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far