') I wa...">

JQuery: how to return an added item

I am using jQuery API append() to add a new element:

$(selector).append('<div class="test"></div>')

I want the expression to return the element just added for my future use, but it returns $(selector) . So, how can I let jQuery return the just added item to avoid reselection?

+6
source share
7 answers

I believe the way to do this is to use appendTo()

Then you could do

 $('<div class="test"></div>').appendTo(selector).css('background','blue'); 

or whatever you wanted to do.

This will cause the div you just added a blue background.

+6
source

You can just save the link to it. Keep in mind that you must do all your manipulations with $div before adding it to an element that is part of the DOM to avoid a few skews.

 var $div = $('<div class="test"></div>'); $(selector).append($div); 
+2
source

You can create an element regardless of append by passing the html string to the jQuery function:

 $('<div class="test"></div>'); 

You can use this either in append

 $(selector).append(/* $div = */$('<div class="test"></div>').… ); 

or appendTo

 /* $div = */$('<div class="test"></div>').appendTo(selector).… ; 

or you just divide them into two statements.

+2
source

That might work too.

 <div class="inner">hellworld</div> $('.inner').append('<p>paragraph</p>'); 

this inserts two new s and existing as the last three child nodes of the body

 var $newdiv1 = $('<div id="object1"/>'), newdiv2 = document.createElement('div'), existingdiv1 = document.getElementById('foo'); $('body').append($newdiv1, [newdiv2, existingdiv1]); 
0
source

Please, try

 $(selector).append('<div class="test"></div>').find('div.test:last-child') 
0
source

You can return it by adding the childern jQuery function, as in this jsfiddle example

 $(selector).append('<div class="test"></div>').children('.test'); 

or you can use the prependTO jQuery function, as in this jsfiddle example:

 $('<div class="test"></div>').prependTo(selector); 
0
source

Perhaps you can try either

 var elt = $('<div class="test"></div>'); $(selector).append(elt); 

Or using appendTo instead of append, and then connect everything you need (show () in the example below)

 $('<div class="test"></div>').appendTo($(selector)).show() 
-1
source

All Articles