jQuery: Change html of element added with append()

Using jQuery, how can I add text to an element I add using append?

Can this be done with one line?

In the example below, the text is NOT added to the paragraph that is created with append()

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {
  $('div').append('<p />').html('This text should in inside the p with a red background');

<style type="text/css">

div {
margin: 50px auto;
padding: 30px;
border: 1px solid #000;
background: #aaaaff;
width: 500px;

p {
width: 200px;
background: #ffaaaa;
margin: 50px auto;
padding: 30px;
border: 1px solid red;





Open in new window

LVL 16
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Line 8 should read :

$('div').append('<p>This text should in inside the p with a red background</p>');

Open in new window

Example : http://sdparkes.co.uk/ee_ex/jquery_append.php
Have just changed the page slightly so you can click the button to see the append happen...
another one :
$('div').append(  $('<p />').html('This text should in inside the p with a red background')  );

Open in new window

$('div').append('<p />').children("p:last").html('This text should in inside the p with a red background');

Open in new window

because : $('div').append('<p />')
return a ref on the div and not on the p

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.