jQuery replaceWith() Method

jQuery | replaceWith() Method: Learn about the jQuery replaceWith() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 18, 2022

replaceWith() Method

The replaceWith() is a jQuery's built-in method. It helps to replace the selected content with some new HTML elements and content. The replaceWith() method only replaces the selected element on the document. Therefore, this method is a lot useful when you want to select only a specific element and replace it with a new element. This method can be preserved as the find & replace the property of MS Word, where we can find a specific word and replace it with some new word in the document.

replaceWith() Method Syntax

$('selector').replaceWith('New Content',function());

The replaceWith() method accepts three parameters – the new content, the element selected & function. The content can be defined along with the HTML tag and its properties over here. The element to be replaced is given through its selector, and hence, helps to replace it with the new content mentioned. The function can be defined (which is optional) and can be executed when the method gets triggered. This method then returns the new HTML element in place of the old element present.

The following example shows the implementation of the replaceWith() method, where when the button is clicked, it replaces the matched element with some new content.

jQuery replaceWith() Method Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
      .display{
      font-size: x-large;
      font-weight: bolder;
      margin: 20px;
      }
    </style>
  </head>
  
  <body>
    <h2>jQuery - Replace With</h2>
    <p>Click the button to replace element <b>with</b> the specified content.</p>
    <button>Replace With</button>
    <hr>
    <img style="height:200px" id="myImg" src="https://media.istockphoto.com/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=">
    <div class="display" style="color: brown;">Welcome to Include Help !!!</div>
    <div>This is an example of replace with method in jQuery.</div>
    <hr>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('button').click(function(){
            $('div:first').replaceWith('<p class="display" style="color: purple;">Thanks For Visiting !!!</p>');
        })
    });    
  </script>
</html>

Output:

Example 1: jQuery replaceWith() Method



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.