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?

6
  • 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? Commented Feb 19, 2013 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" Commented Feb 19, 2013 at 22:05
  • @bobbybee: Do you know if push is part of the official jQuery API? Commented Feb 19, 2013 at 22:09
  • @cdmckay I doubt it. It's standard ECMAScript (what JS and AS3 are based off of), so probably JavaScript. Commented Feb 19, 2013 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: stackoverflow.com/questions/14524024/jquery-push-function Commented Feb 19, 2013 at 22:13

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Doh, rookie mistake. I forgot that it always returns a new set.
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)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.