Jquery add function not working properly

The following snippet does not work.

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

HTML has a div element, and it is added correctly to the div. But the collection of divs is not added to the empty jquery object. Any ideas what is wrong with this?

+5
source share
3 answers

.addwill not change the original object. Try:

empty = empty.add(divs);
+22
source

You can do

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

Per jquery doc,

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

var pdiv = $("p");
pdiv.add("div");  // WRONG, pdiv will not change
0
source

All Articles