.replaceWith()
JQ Home <<
Manipulation <<
.replaceWith()
DOM replacement.
Description
The .replaceWith()
method is used to replace each element in the matched set with the specified content.
- When replacing content with other existing content, the existing content replaces the target by being moved from its old location, not by being cloned.
Syntax
Signature | Description |
---|---|
.replaceWith( newContent ) | Replace each element in the matched set with the specified content. |
.replaceWith( function() ) | A function that returns a DOM element(s), HTML string, or jQuery object to replace each element in the matched set with. |
Parameters
Parameter | Description | Type |
---|---|---|
newContent | A DOM element, HTML string, or jQuery object to replace content with. | Element ,HTMLstring orjQuery |
function() | A function.
|
Function |
Return
A jQuery
object containing the new matched set of elements.
.replaceWith( newContent )
Example
Manip. << Top
Replace each element in the matched set with the specified content.
In the example below when the button is pressed we replace the table row with an id of 'trid3' with new content.
Table Row 1 (id of trid3), Table Data 1 | Table Row 1 (id of trid3), Table Data 2 |
$(function(){
$('#btn9').on('click', function() {
$('#trid3').replaceWith('<tr><td>Replaced content</td><td>Replaced content</td></tr>');
});
});
.replaceWith( function() )
Example
Manip. << Top
A function that returns a DOM element(s), HTML string, or jQuery object to replace each element in the matched set with.
In the example below when you press the button we replace the table row with an id of 'trid5' with the table row returned from the function with an id of 'trid5. Notice how the table row is moved and not cloned as described in the description above.
Table Row 1, Table Data 1 | Table Row 1, Table Data 2 |
Table Row 2 (id of trid4), Table Data 1 | Table Row 2 (id of trid4), Table Data 2 |
Table Row 3 (id of trid5), Table Data 1 | Table Row 3 (id of trid5), Table Data 2 |
$(function(){
$('#btn10').on('click', function() {
$('#trid4').replaceWith( function() {
return '#trid5';
});
});
});
Related Tutorials
jQuery Intermediate Tutorials - Lesson 5 - DOM Removal & Replacement