Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get jquery's .append() to return the wrapped set containing the appended object not the container

Tags:

jquery

append

I want to append an html element to a div and have jquery return me the wrapped set that contains the element I just appended and not the wrapped set containing the div

So my html:-

...

<div id="somediv">Some other elements...</div>

...

javascript:-

var jqueryObj = $('#somediv').append('<p>Hello, World!</p>');

alert(jqueryObj.html());

I'd like this to alert me with 'Hello, world' not 'Some other elements...<p>Hello, World!</p>'

like image 639
rgvcorley Avatar asked Feb 14 '12 11:02

rgvcorley


People also ask

Does jQuery append return the element?

Element. append() has no return value, whereas Node. appendChild() returns the appended Node object.

What is the difference between append and appendTo in jQuery?

append() , the selector expression preceding the method is the container into which the content is inserted. With . appendTo() , on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

Which of the following are uses of appendTo?

Definition and Usage The appendTo() method inserts HTML elements at the end of the selected elements. Tip: To insert HTML elements at the beginning of the selected elements, use the prependTo() method.


2 Answers

Use .appendTo() instead of .append().

var jqueryObj = $('<p>Hello, World!</p>').appendTo('#somediv');
alert(jqueryObj.html()); // '<p>Hello, World!</p>'
like image 88
Sharon Avatar answered Sep 20 '22 17:09

Sharon


Switch them around, and use the .appendTo() function. Like so:

var jqueryObj = $('<p>Hello, World!</p>').appendTo('#somediv');

Working DEMO

like image 45
Anthony Grist Avatar answered Sep 21 '22 17:09

Anthony Grist