January 05, 2025
Replace an element with using replaceWith method in jQuery
In jQuery, we can use the replaceWith() method to replace the selected elements with new content (text or html tags). It completely overwrite the existing element. Below is example of replaceWith() methods:
replaceWith() method example
<html>
<head>
<title>Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="sourceElem">
<p>Source Content</p>
</div>
<br>
<button id="btnReplace">Replace example</button>
<script>
$(document).ready(function () {
$('#btnReplace').on('click', function () {
$("#sourceElem").replaceWith("<p>New paragraph replacing the element.</p>");
});
});
</script>
</body>
</html>