Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change in .appendTo() in jquery1.9.1

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.

like image 238
Annapoorni D Avatar asked Nov 13 '22 01:11

Annapoorni D


1 Answers

"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.

like image 152
Faust Avatar answered Nov 15 '22 12:11

Faust