Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




HTML METHODS - replaceWith()


The replaceWith() method in JQuery is used to replace an HTML element with new content.


Example :



<html>
    <head>
    	<title> My First Programme </title>
  	</head>

	<style>
    	div {
        	background-color: violet;
        }
    </style>
  	<body>
    	<h1> JQuery </h1>
    	<p>New Code</p>
    	
    	<button> Click Here </button>
    	
      	<script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script>
	  
      	<script>
      
      		$('button').click( function() {
				$('p').replaceWith("<div>Hello World</div>");
			});
			
      	</script>      
   </body>
</html>


Output :




So, in the above code, we have a <p> element,


<p>New Code</p>

And we are going to replace it with a new <div> element.


<div>Hello World</div>

And we have achieved it using the JQuery statement,


$('button').click( function() {
	$('p').replaceWith("<div>Hello World</div>");
});

All we are doing is, using the replaceWith() method on the <p> element, to replace the <p> element with the <div> element.


$('p').replaceWith("<div>Hello World</div>");

And we got the <p> element replaced with the <div> element violet in color.


And why is the color violet?


Because we have set the style property for <div> element.


<style>
	div {
		background-color: violet;
	}
</style>