2

In the jQuery add documentation, it lists an add(html) overload which describes the html argument as:

An HTML fragment to add to the set of matched elements.

Since there is already an add(element) overload, I assume this means that you pass it an HTML string, as in:

var set = $();
set.add("<div></div>");
document.write(set.length); // prints 0

However, when this code is run, it has no effect on the jQuery wrapped set. What am I missing?

cdmckay
  • 31,832
  • 25
  • 83
  • 114
  • I doubt this is what you are looking for, but if you use the push method rather than the add method, it DOES result in a length of 1. May I ask what the purpose of this code is? – bobbybee Feb 19 '13 at 22:04
  • in that link just a few scrolls down it says this very clearly: "The following will not save the added elements, because the .add() method creates a new set and leaves the original set in pdiv unchanged: 12 var pdiv = $("p");pdiv.add("div"); // WRONG, pdiv will not change" – Kyle C Feb 19 '13 at 22:05
  • @bobbybee: Do you know if `push` is part of the official jQuery API? – cdmckay Feb 19 '13 at 22:09
  • @cdmckay I doubt it. It's standard ECMAScript (what JS and AS3 are based off of), so probably JavaScript. – bobbybee Feb 19 '13 at 22:11
  • @bobbybee: It's standard ECMAScript for Arrays, not jQuery objects. Anyway, I can't find it on the jQuery site, and this post discourages its use: http://stackoverflow.com/questions/14524024/jquery-push-function – cdmckay Feb 19 '13 at 22:13
  • @cdmckay Ah, k. I spend much more time in Flash development that it just seems natural to write .push(obj) now :) – bobbybee Feb 19 '13 at 22:22

3 Answers3

3

You got to set the return of add to the set like below,

set = set.add("<div></div>");

.add returns the collated jQuery object which you can chain, it doesn't really add it to the original object.

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
1

It works fine if you define it in a single line: http://jsfiddle.net/s2zQr/3/

var set = $().add("<div></div>");
document.write(set.length);

as @Pavel Chernov noted... the .add() method creates a new set (and that's why your count never updated)

scunliffe
  • 62,582
  • 25
  • 126
  • 161
1

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

so your set is still empty

starowere
  • 113
  • 4