最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - MergeJoin 2 jQuery sets - Stack Overflow

programmeradmin3浏览0评论

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 ?

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 ?

Share Improve this question edited Jul 4, 2011 at 3:57 alex asked Nov 15, 2009 at 23:55 alexalex 490k204 gold badges889 silver badges991 bronze badges 2
  • yes it would, i also thought the other day same thing now i see that i'm not alone:) – Sinan Commented Nov 16, 2009 at 0:09
  • 1 $('#my div, #somewhere ul').addClass('my-new-class'); is actually fine, as is $div.add($ul).addClass('my-new-class'); – ChaseMoskal Commented Jan 14, 2014 at 2:35
Add a comment  | 

3 Answers 3

Reset to default 19

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.

I know this is very very late, but you can also do the following:

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

try

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

look here

发布评论

评论列表(0)

  1. 暂无评论