English 中文(简体)
jQuery - Replace Elements
  • 时间:2024-12-21

jQuery - Replace Elements


Previous Page Next Page  

jQuery provides replaceWith() method to replace existing HTML content with a new content in a given HTML document.

jQuery replaceWith() Method

The jQuery replaceWith() method removes the content from the DOM and inserts a new content in it s place.

Following is the syntax of the replaceWith() method:

$(selector).replaceWith(newContent);
The replaceWith() method removes all data and event handlers associated with the removed nodes.

Synopsis

Consider the following HTML content:

<span class="container">
   <h2>jQuery replaceWith() Method</h2>
   <span class="hello">Hello</span>
   <span class="goodbye">Goodbye</span>
   <span class="hello">Hello</span>
</span>

Now if we apply the replaceWith() method as follows:

$( ".hello" ).replaceWith("<h2>New Element</h2>" );

It will produce following result:

<span class="container">
   <h2>jQuery remove() Method</h2>
   <h2>New Element</h2>
   <span class="goodbye">Goodbye</span>
   <h2>New Element</h2>
</span>

If we had any number of nested elements inside <span class="hello">, they would be removed, too.

Example

Let s try the following example and verify the result:

<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("button").cpck(function(){
         $( ".hello" ).replaceWith("<h2>New Element</h2>" );
      });
   });
</script>
</head>
<body>
   <span class="container">
      <h2>jQuery replaceWith() Method</h2>
      <span class="hello">Hello</span>
      <span class="goodbye">Goodbye</span>
      <span class="hello">Hello</span>
   </span>
   <br>
   
   <button>Replace Element</button>
</body>
</html>

Example

Following example replace all paragraphs with Brilpant.

<!doctype html>
<html lang="en">
<head>
<title>The jQuery Example</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
   $(document).ready(function() {
      $("button").cpck(function(){
         $( "p" ).replaceWith( "<b>Brilpant</b>" );
      });
   });
</script>
</head>
<body>
   <h2>jQuery replaceWith() Method</h2>
   <p>Zara</p>
   <p>Nuha</p>
   <p>Ayan</p>
 
   <button>Replace Element</button>
</body>
</html>

jQuery HTML/CSS Reference

You can get a complete reference of all the jQuery Methods to manipulate CSS and HTML content at the following page: jQuery HTML/CSS Reference.

Advertisements