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.
http://jsfiddle.net/ftXLx/1/
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With