Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery searching multiple levels of children

Tags:

jquery

I have a parent div class called common-end.

I have many div's of this class, an example of how it looks is:

<div class="item question common-end">
    <label>label</label>
    <div>
       <textarea name="name1" id="text1" class="deep-item form-control input-lg" rows="3"></textarea>
    </div>
</div>

Not all common-end div's have this structure. There might be multiple layers of nesting.

The only thing I will know for sure, is that SOMEWHERE inside common-end there will be something with the class deep-item (in this case it's on the textarea).

What is a jQuery selector I can use to find deep-item SOMEWHERE inside common-end?

Thanks

like image 747
b85411 Avatar asked Apr 16 '15 01:04

b85411


1 Answers

As RyanW mentioned, the simplest selector is that similar to a CSS selector:

var $deepItems = $('.common-end .deep-item');

However, I should mention that the way jQuery works, in this scenario, is to search right to left. So, if you have .deep-item elements in elements other than .common-end elements (or just simply have very few .common-end elements) you should give jQuery the opportunity to scope it (making it slightly faster):

var $deepItems = $('.deep-item', '.common-end')
// equivalent to:
var $deepItems = $('.common-end').find('.deep-item')

This allows jQuery to simply find all .common-end elements first, then begin searching within for .deep-item (instead of finding all .deep-items and confirming they're nested within a .common-end).

This may not be as big an issue, given you have specific classes to search for. However, if you were starting with a class and grabbing a specific tag, it could become a problem. Picture the following:

$('.common-end div');

Which would grab every <div> on the page, then check if it's a descendent of .common-end.

like image 165
Brad Christie Avatar answered Sep 17 '22 11:09

Brad Christie