Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I combine a variable and a selector in Jquery?

Tags:

jquery

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/

like image 623
Sam Avatar asked Jun 03 '13 15:06

Sam


1 Answers

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...

like image 106
Denys Séguret Avatar answered Sep 29 '22 22:09

Denys Séguret