Reputation: 9990
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
Upvotes: 10
Views: 14336
Reputation: 101594
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-item
s 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
.
Upvotes: 11
Reputation: 1672
In jQuery you use selectors in the same way you use them in css.
$('.common-end > .deep-item') //this will select only direct children
$('.common-end .deep-item') //this will select all children, even if nested under multiple levels
According to your question, you need the second one.
Upvotes: 2
Reputation: 8513
$('.common-end .deep-item')
This will return all deep-item's within a common-end. If there is a specific on you are looking for, you can do something like below:
var el = $(<selector to the common-end i care about);
var deepItem = el.find('.deep-item');
Upvotes: 3