I use jQuery API append()
to add a new element:
$(selector).append('<div class="test"></div>')
I want the expression return the just appended element for my further use, however it returns $(selector)
. So, how can I let jQuery to return the just appended element to avoid re-selecting it?
I use jQuery API append()
to add a new element:
$(selector).append('<div class="test"></div>')
I want the expression return the just appended element for my further use, however it returns $(selector)
. So, how can I let jQuery to return the just appended element to avoid re-selecting it?
7 Answers
Reset to default 10I believe the way to do that would be to use appendTo()
Then you could do
$('<div class="test"></div>').appendTo(selector).css('background','blue');
or whatever you wanted to do.
That would cause the div
you just appended to have a blue background.
You can just store a reference to it. Keep in mind that you should do all your manipulations with $div
before appending it to an element that is part of the DOM
to avoid multiple reflows.
var $div = $('<div class="test"></div>');
$(selector).append($div);
You can create the element independently from append
by passing the html string to the jQuery
function:
$('<div class="test"></div>');
You can use that either in the append
$(selector).append(/* $div = */$('<div class="test"></div>').… );
or with appendTo
/* $div = */$('<div class="test"></div>').appendTo(selector).… ;
or you just separate them into two statements.
This can work too.
<div class="inner">hellworld</div>
$('.inner').append('<p>paragraph</p>');
this will insert two new s and an 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]);
Please try this
$(selector).append('<div class="test"></div>').find('div.test:last-child')
You can return it by add childern
jQuery function as in this example jsfiddle
$(selector).append('<div class="test"></div>').children('.test');
or you can use prependTO
jQuery function as in this example jsfiddle :
$('<div class="test"></div>').prependTo(selector);
Maybe you can try either
var elt = $('<div class="test"></div>');
$(selector).append(elt);
Or using appendTo instead of append, and then chain whatever you need (show() in the example below)
$('<div class="test"></div>').appendTo($(selector)).show()
$('<div class="test"></div>').appendTo(selector)
? – Jeff Shaver Commented Apr 10, 2013 at 12:09