Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge/Join 2 jQuery sets

Look at this code for example...

var $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 ?

like image 314
alex Avatar asked Nov 15 '09 23:11

alex


1 Answers

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. Note that $b remains unchanged.

like image 168
Crescent Fresh Avatar answered Nov 09 '22 02:11

Crescent Fresh