Reputation: 26281
How can an element be replaced, and then appended to?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Testing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
<style type="text/css"></style>
<script type="text/javascript">
$(function(){
//Appends as desired
$('.dont-replace')
.append($('<p/>', {'class': 'a'}))
.append($('<p/>', {'class': 'b'}));
//Replaces but doesn't append
$('.replace-once')
.replaceWith($('<div/>'))
.append($('<p/>', {'class': 'a'}))
.append($('<p/>', {'class': 'b'}));
//Replaces but doesn't append
$('.replace-once')
.replaceWith($('<div/>')
.append($('<p/>', {'class': 'a'}))
.append($('<p/>', {'class': 'b'}))
);
//Replaces but doesn't append
$('.replace-multiple').each(function() {
$(this).replaceWith($('<div/>'))
.append($('<p/>', {'class': 'a'}))
.append($('<p/>', {'class': 'b'}));
})
//Replaces but doesn't append
$('.replace-multiple').each(function() {
$(this).replaceWith($('<div/>')
.append($('<p/>', {'class': 'a'}))
.append($('<p/>', {'class': 'b'}))
);
})
//No such thing as the replace method
($('<div/>'))
.append($('<p/>', {'class': 'a'}))
.append($('<p/>', {'class': 'b'}))
.replace($('.replace-once2'));
});
</script>
</head>
<body>
<span class="dont-replace"></span>
<span class="replace-once"></span>
<span class="replace-multiple"></span>
<span class="replace-multiple"></span>
<span class="replace-once2"></span>
</body>
</html>
Upvotes: 0
Views: 86
Reputation: 150010
Append the children to the new div element before you pass it to the .replaceWith()
method:
$('.replace').replaceWith(
$('<div/>')
.append($('<p/>', {'text': 'a', 'class': 'a'}))
.append($('<p/>', {'text': 'b', 'class': 'b'}))
);
// Check the structure of the resulting HTML:
console.log($(".container").html());
.a { background-color: red; }
.b { background-color: yellow; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
<span class="replace">I will be replaced.</span>
</div>
(If you just chain .append()
after .replaceWith()
like you had tried, then you are appending to the original element that just got replaced.)
Upvotes: 1
Reputation: 3270
I deleted my previous answer. Here's the situation. Because you're using .replaceWith() it removes all data from the DOM and adds it again. Therefore, when you try to append to what has been replaced it doesn't work because it wants to refer to the original DOM element that is not working. You're going to have to use delegation if you want this to work using replace.
Read the .replaceWith() documentation.
Upvotes: 0