Jquery find in tree

Asked

Viewed 231 times

6

I have the following context:

<div class='pai' id='item'>

    <div class='form'>

       <div class='filho' id='item1'>

            <div class='filho' id='item3'>

            </div>

       </div>

       <div class='filho' id='item2'>

       </div>

    </div>

</div>

I’d like to get the elements .filho of first level in relation to the element .pai. Soon I would have only 2 results (item1 and item2) disregarding item3.

I must do this without regard to id, because I used him on this example just to make the question clearer. If possible, also disregard the form.

4 answers

4


We may consider the form?

If yes the dial would be like this

$('.pai > .form > .filho')

The selector > considers only the father’s direct children disregarding the hierarchy.

Functional example in http://jsfiddle.net/776jy0hs/

More about this in https://api.jquery.com/child-selector/

Edited

To totally disregard any kind of hierarchy and take the first children, you can do so:

$('.pai .filho:first-of-type');

This will select all the father’s children, but only the first of their kind

Jsfinddler updated http://jsfiddle.net/776jy0hs/1/

More about in https://api.jquery.com/first-of-type-selector/

  • Thank you for the @Erick-gallani reply , but I would not like to consider the form, I’ll edit the question.

  • @Jedaiasrodrigues is there a predefined hierarchy? Or is it changeable? Type will always be the class . parent and dpeois an element and then the child elements?

  • @Jedaiasrodrigues see the update in my reply

3

The combination element Child (P > F) selects only first-level children.

As you have a div class form in the first level, you could pick up the children as follows:

$("div.pai > div > .filho")

Thus, an array containing the children of id "item1" and "item2" is returned, ignoring the "item3", which in this case is the child of item1.

2

It can be like that too.

$('div.pai').find('.filho').siblings('.filho');

Search in the tree the .filho(s) and takes only the first-degree.

  • But like I said in the question, I need to all children of the first level in relation to the father.

  • I edited Jedaiah.

0

you can do it this way:

$(".pai").children().children(".filho");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.