Sam
Sam

Reputation: 1243

Can I combine a variable and a selector in 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/

Upvotes: 9

Views: 12850

Answers (3)

ExceptionLimeCat
ExceptionLimeCat

Reputation: 6400

Could you just select it like this:

$('.top .middle').click();

Upvotes: 0

BrunoLM
BrunoLM

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

Denys S&#233;guret
Denys S&#233;guret

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

Related Questions