Reputation: 1243
Say I have this HTML:
<div class="top">top
<div class="middle">middle
<div class="bottom">bottom</div>
middle</div>
top</div>
<div class="middle">outside middle</div>
Is there a way to create a variable for a selector and then use it as part of another selector? This is what I'm trying to do, but this does't work :
$top = $('.top');
$($top + ' .middle').click(function(){
$(this).toggleClass('green');
});
I'm sure I don't need to re-select .top as that's what the variable did, so I'm sure I need to do something with $top, I'm just not sure what.
Upvotes: 9
Views: 12850
Reputation: 6400
Could you just select it like this:
$('.top .middle').click();
Upvotes: 0
Reputation: 100331
You can use find()
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
$top.find(".middle");
Upvotes: 5
Reputation: 382150
Use
$('.middle', $top)
or
$top.find('.middle')
You could also have simply combined the selectors, which are strings, with
$($top.selector + ' .middle')
but this would only be slower and less readable...
Upvotes: 22