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

javascript - jquery add function doesn't work as expected - Stack Overflow

programmeradmin2浏览0评论

The following snippet doesn't work.

var empty = $();
var divs = $("div");
empty.add(divs);

There is a div element in the HTML and it is added correctly to divs. But the divs collection is not added to the empty jquery object. Any ideas what`s wrong with that?

The following snippet doesn't work.

var empty = $();
var divs = $("div");
empty.add(divs);

There is a div element in the HTML and it is added correctly to divs. But the divs collection is not added to the empty jquery object. Any ideas what`s wrong with that?

Share Improve this question asked Aug 14, 2012 at 7:23 DirkDirk 1,0308 silver badges17 bronze badges 1
  • It works as it's documented. – alex Commented Aug 14, 2012 at 7:39
Add a comment  | 

3 Answers 3

Reset to default 23

.add won't change the original object. Try:

empty = empty.add(divs);

You can do

var empty = $.extend($(), $('div'));

Per Jquery doc,

The following will not save the added elements, because the .add() method creates a new set and leaves the original set in pdiv unchanged:

var pdiv = $("p");
pdiv.add("div");  // WRONG, pdiv will not change
发布评论

评论列表(0)

  1. 暂无评论