Reputation: 17467
I know I can do this
$('.intro').append('<p>this is my text</p>');
but how can I text to the new element by chaining it
$('.intro').append('<p></p>').text('this is my text');
Upvotes: 3
Views: 1241
Reputation: 1969
It should work like you want! :)
$('.intro').append('<p></p>').find('p:last').text('this is my text');
You also miss a single quote there.
This is more correct where jQuery will wait till append() is really done 100%:
note: the above method is work, but harsh
$('.intro').append('<p></p>').promise().done(function() {
$(this).find('p:last').text('this is my text');
});
Upvotes: -1
Reputation: 62676
You can use one of the two:
$('.intro1').append($('<p/>').text('this is my text'));
$('.intro2').append('<p></p>').find('p:last-child').text('this is my text');
div {
border: 1px solid red;
margin: 5px;
}
p {
border: 1px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="intro1"></div>
<div class="intro2"></div>
The problem is that the append
returns the parent element (and not the one you just added).
Upvotes: 1
Reputation: 21470
The .append()
call returns the element that run it (the .intro
element in your code), and not the appended element (p
in your code).
If you want you can separate the creation the appending of the p
element like so:
var $p = $('<p />').append('your text goes here');
// and then you can:
$('.intro').append($p); // this returns the '.intro' element
// or
$p.appendTo($('.intro')); // this returns the $p element...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="intro"></div>
Upvotes: 5
Reputation: 11
Okay, let me help If you have to append and attach a text to id, do it like this
$("<p> Hello this is a text</p>").appendTo($("#item"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="item">Append now</div>
Upvotes: 0