jQuery replaceWith() method – For replacing HTML elements in the DOM

jQuery replaceWith() method – For replacing HTML elements in the DOM

If you want to replace one or more HTML elements on the DOM then use jQuery replaceWith() method.

Syntax of jQuery replaceWith() method

$(selector).replaceWith(content,function(index));
Parameter Description
content

Required.

Specifies the content to insert (can contain HTML tags).

function(index)

Optional.

Specifies a function that returns each selected element’s content one by one.

index – Returns the index position of the element.

jQuery replaceWith – Replacing Paragraphs with Words

I have some paragraph elements and I will replace each of them with Good Morning.

<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>

The jQuery replaceWith code will be:

$("p").replaceWith("Good Morning");

jQuery replaceWith – Replacing Paragraphs with Words using function parameter

In this example I will use the function parameter to replace the paragraph element.

<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>
<p>Paragraph</p>

The jQuery replaceWith() code would be:

$("p").replaceWith(function (n) {
    return "<h2>This element index is " + n + ".</h2>";
});

So the above code will replace each p element with their index number. Index number will start from 0.

Download source code:

Download

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate

Leave a Reply

Your email address will not be published. Required fields are marked *