How to Replace String, Text, or HTML in jQuery?

In this blog, I will show you How to Replace String, Text, or HTML in jQuery?

We can replace HTML elements using jQuery .replaceWith() method. With the jQuery replaceWith() method, we can replace each element in the set of matched elements with the provided new content and return the set of removed elements. The .replaceWith() method removes content from the DOM and inserts new content in its place with a single call.

Syntax:


replaceWith()

Example 1: We get the element we need to replace and write a new element in its place.
Code:

<!DOCTYPE html>
<html>
  <head>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
		</script>
    <script>
      $(document).ready(function(){
        $("button").click(function(){
          $("p").replaceWith
          ("<div style='width:200px;height:100px;\
background-color:blue;text-align:center;\
vertical-align:middle;display:table-cell'>\
<strong>New Div</strong></p>");
        });
      });
    </script>
  </head>
  <body>
    <p>Example Paragraph.</p>
    <button style="margin: 20px 0px;">
      Click To Replace
    </button>
  </body>
</html>

Output:

Example 2: We can also replace one HTML element with another existing HTML element.

<!DOCTYPE html>
<html>
  <head>
    <script src=
           "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
    </script>
    <script>
      $(document).ready(function(){
        $("button").click(function(){
          $("p").replaceWith($("h1"))
        });
      });
    </script>
  </head>
  <body>
    <p>Example paragraph.</p>
    <button style="margin: 20px 0px;">
      Click To Replace
    </button>
    <h1>H1 heading tag</h1>
  </body>
</html>

Output:

Hope this blog is helpful for you, Thanks for reading this blog.

How to Replace String or Text or HTML in jQuery?expoundsofttechsolution

ghb