Dirk
Dirk

Reputation: 1020

jquery add function doesn't work as expected

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?

Upvotes: 5

Views: 1674

Answers (3)

Feng Xi
Feng Xi

Reputation: 1

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

Upvotes: 0

thecodeparadox
thecodeparadox

Reputation: 87073

You can do

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

Upvotes: 3

xdazz
xdazz

Reputation: 160833

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

empty = empty.add(divs);

Upvotes: 23

Related Questions