I am trying to understand the change in behavior of .appendTo() api in jquery 1.9.1 version from previous versions. In the upgrade guide it says
As of 1.9, these methods(
.appendTo
,.insertBefore
,.insertAfter
, and.replaceAll
) always return a new set, making them consistently usable with chaining and the.end()
method. Prior to 1.9, they would return the old set only if there was a single target element. Note that these methods have always returned the aggregate set of all elements appended to the target elements.
I tried with a simple usage of this api
<div class="test">hello
</div>
var $ = jQuery.noConflict();
var a =$("<p> hi </p>").appendTo("div.test").attr("style","background-color:red");
console.log(a);
Here is the fiddle link
I am appending a paragraph element to a div and then changing the background of the resulting element. I tried this with both 1.7.2 and 1.9.1 in both the cases the result after appending is the paragraph element.
But it has been explained in document that prior to 1.9 it will return old set(in my example old set refers to the div element I believe). I am definitely having a wrong idea about this.
Please help in correcting my understanding.
"these methods have always returned the aggregate set of all elements appended" means it returns the jQuery collection on which appendTo()
was called -- not the set passed into the function.
This would be the paragraph, in your case. So it should return that regardless of the jQuery version you are using as long as "div.test" is a single-element target (and, by the way, don't you mean $('div.test')
?), or if using v 1.9, as long as "div.test" returns at least one element.
This is the case for jQuery chaining with most calls -- that the funciton returns the element it was called on so you may continue doing other things with it. I beleive this is the case with all of the manipulation subset of jQuery functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With