13

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>'

rgvcorley
  • 2,883
  • 4
  • 22
  • 41
  • you would have to save the html content before you append the new content, and after appending remove the content that you saved from the new. But why don't you simply save the value of what you are appending to a variable and use .text() method ? – mas-designs Feb 14 '12 at 11:48
  • Sorry, this was mearly a test case that I setup - I don't actually want the text of the containing paragraph, I want to apply a jquery ui dialog to the jquery object – rgvcorley Feb 14 '12 at 11:57

4 Answers4

27

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

var jqueryObj = $('<p>Hello, World!</p>').appendTo('#somediv');
alert(jqueryObj.html()); // '<p>Hello, World!</p>'
Sharon
  • 919
  • 7
  • 7
3

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

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

Working DEMO

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
0
var jqueryObj = $('#somediv').append('<p>Hello, World!</p>');

alert(jqueryObj.find("p").html());
mgraph
  • 15,238
  • 4
  • 41
  • 75
0

Try this:

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

alert(jqueryObj.html());

What you want is the variable to actually hold the newly created object, not the div into which you added it.

Gilthans
  • 1,656
  • 1
  • 18
  • 23