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?
The returned element from append() is the container and not the new element.
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.
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.
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.
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.
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