.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
newContentA DOM element, HTML string, or jQuery object to replace content with.Element,
HTMLstring or
jQuery
function()A function.
  • The callback is fired in the context of the current element in the set, so the keyword this refers to that element.
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.

Table1 For Testing The .replaceWith( newContent ) Signature
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>'); 
  });
});


Press the button below to action the above code:

.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.


Table2 For Testing The .replaceWith( function() ) Signature
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';
    }); 
  });
});


Press the button below to action the above code:

Related Tutorials

jQuery Intermediate Tutorials - Lesson 5 - DOM Removal & Replacement