From jQuery JavaScript Library
« Back to Manipulation
replaceWith( content )
Replaces all matched elements with the specified HTML or DOM elements.
Arguments:| content | String, Element, jQuery | |
|---|
| Content to replace the matched elements with. |
Examples:| Name | Type |
On click, replace the button with a div containing the same word.
$("button").click(function () {
$(this).replaceWith("<div>" + $(this).text() + "</div>");
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("button").click(function () {
$(this).replaceWith("<div>" + $(this).text() + "</div>");
});
});
</script>
<style>
button { display:block; margin:3px; color:red; width:200px; }
div { color:red; border:2px solid blue; width:200px;
margin:3px; text-align:center; }
</style>
</head>
<body>
<button>First</button>
<button>Second</button>
<button>Third</button>
</body>
</html>
Replace all the paragraphs with bold words.
$("p").replaceWith("<b>Paragraph. </b>");
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("p").replaceWith("<b>Paragraph. </b>");
});
</script>
</head>
<body>
<p>Hello</p>
<p>cruel</p>
<p>World</p>
</body>
</html>
Replace all the paragraphs with empty div elements.
$("p").replaceWith(document.createElement("div"));
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("p").replaceWith(document.createElement("div"));
});
</script>
<style>
div { border:2px solid blue; margin:3px; }
</style>
</head>
<body>
<p>Hello</p>
<p>cruel</p>
<p>World</p>
</body>
</html>
On click, replace each paragraph with a jQuery div object that is already in the DOM. Notice it doesn't clone the object but rather moves it to replace the paragraph.
$("p").click(function () {
$(this).replaceWith($("div"));
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="../jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("p").click(function () {
$(this).replaceWith($("div"));
});
});
</script>
<style>
div { border:2px solid blue; color:red; margin:3px; }
p { border:2px solid red; color:blue; margin:3px; cursor:pointer; }
</style>
</head>
<body>
<p>Hello</p>
<p>cruel</p>
<p>World</p>
<div>Replaced!</div>
</body>
</html>