Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: how to return the appended element

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?

like image 882
Shuping Avatar asked Apr 10 '13 12:04

Shuping


People also ask

Does jQuery append return the element?

The returned element from append() is the container and not the new element.

What is the reverse of append in jQuery?

jQuery prepend() The jQuery prepend() method is used to insert the specified content at the beginning (as a first child) of the selected elements. It is just the opposite of the jQuery append() method.

What is the difference between the append () and after () methods in jQuery?

The . append insert the parameter element inside the selector element's tag at the last index position, whereas the . after puts the parameter element after the matched element's tag.

What is append and prepend in jQuery?

The prepend() method inserts specified content at the beginning of the selected elements. Tip: To insert content at the end of the selected elements, use the append() method.


1 Answers

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

like image 50
Jeff Shaver Avatar answered Sep 30 '22 22:09

Jeff Shaver