views:

226

answers:

3

Look at this code for example

$div = $('#my div');

$ul = $('#somewhere ul');

How can I perform a jQuery method on both of them? For example, would this work? What is best practice here?

$($div, $ul).addClass('my-new-class');

Wouldn't that search $div under a context of $ul ?

Thank you

A: 

try

$('#my div, #somewhere ul').addClass('my-new-class');

look here

gpilotino
I know that will work, but sometimes I set up the 2 caches at the beginning of the script, and I would like to avoid redefining them later within methods etc.
alex
+6  A: 

jQuery provides the add method for this. The most common case is to add more elements to the jQuery set that match a given selector (passed to add), but you can use it to perform a standard union of two sets too:

$c = $a.add($b).addClass('foo')

add returns a new wrapped set, containing the merged and unique combination of this and the given set.

Crescent Fresh
Thank you! I knew the answer was lurking out there...
alex
A: 

iYes, It should work with two selectors

Aditya