Reputation: 3935
I have this problem I'm working on which is giving me a headache, because I can't seem to find where the bug is. Here's the markup:
<div class="excerpt">
<p>...</p>
</div>
<div class="bio">
<p>...</p>
</div>
When the user clicks a button, I want to display whatever is in div.bio to show in div.excerpt. Here is my click() function.
$('.button').click( function() {
var bio = $('.bio p');
var excerpt = $('.excerpt');
// empty
excerpt.empty();
// replace
bio.appendTo(excerpt);
});
The problem is that this code removes the paragraphs from the bio during the append. Is there a way to simply append and not remove the elements from the source? Or am I doing something else wrong?
Upvotes: 0
Views: 1581
Reputation: 154
While some of the other answers will probably work, this seems pretty terse.
$('.button').click( function() {
$('.excerpt').html($('.bio').html());
});
Upvotes: 1
Reputation: 211
Try this, as Jon suggested:
$('.button').click( function() {
var bio = $('.bio p');
var excerpt = $('.excerpt');
// empty
excerpt.empty();
// replace
bio.clone().appendTo(excerpt);
});
Upvotes: 1
Reputation: 437376
When you use append
or appendTo
on existing parts of the DOM tree you are actually moving them. As the documentation states,
If an element selected this way is inserted elsewhere, it will be moved into the target (not cloned):
You need to also use clone
to add a copy of the elements to the tree. For example:
bio.clone().appendTo(excerpt);
Upvotes: 4