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