Replacing and removing HTML Elements
Replacing Elements
Jquery has couple of functions to let you replace html element by another html element.
These two functions replaceAll() and replaceWith() allows you to select single or multiple elements and specify the html elements you want to replace them with.
Using replaceWith () to replace element
Suppose on click of a button, you want to replace a <p> element with a <div> element. You can achieve this functionality as
HTML
<p>It will be nice if <strong>this text</strong> appear inside a gray div when the button is clicked.</p>
<br />
<input id="Submit1" value="Replace paragraph by div" type="submit">
or
Jquery
$("#Submit1").click(function () \line$("p").replaceWith("<div>I am a div</div>") ;
);
In the above chunk of code, we are replacing the entire <p> element along with its inner html with div element.
Replacing the element while retaining its HTML content
In previous example, we use the replacewith function to replace the entire paragraph element including its HTML element. But in some case, we might have the requirement to change only the element type while keeping its HTML content intact. i.e Only closing and opening tag should be replaced by a new element tag and not its inner html. This can be achieved as
$("#Submit2").click(function () $("p").replaceWith("<div style=background-color:red>" + $("p").html() + "</div>") ;
);
This code retains the inner HTML content of paragraph element and replaces only the HTML element name.
i.e. <p> is replaced by <div> and </p> is replaced by </div>
Using replaceAll () to replace element
ReplaceAll() function is very similar to replaceWith() function only difference is in its syntax.
For example, below code uses the replaceAll() function to replace a <p> element with a <div> element.
$("#Submit3").click(function () $("<div style=background-color:red>" + $("p").html() + "</div>").replaceAll("p") ;
);
This code is very similar to the preceding one except that the positions of the element tags are changed. This code instructs the browser to select the paragraph element and replace it with the div element having with a red background color.
Removing Elements
replaceAll() and replaceWith() functions can also be used to remove elements simply by providing no parameters or passing nothing in the replacewith function.
Below code uses replaceWith() function to remove all <p> elements without replacing them with anything.
$("#Submit5").click(function () $("strong").replaceWith() ;
);
Same functionality can be achieved as
$("#Submit5").click(function () $().replaceAll("strong") ;
);
Jquery provides us one more function remove() to achieve the same functionality. Below example uses the remove function to remove HTML element.
HTML
<strong>Remove me.</strong>
<br />
<em>Don’t remove me.</em>
<br />
<input id="Submit4" value="Remove strong remove function" type="submit"><br/><br/>
Jquery
$("#Submit4").click(function () $("strong").remove() ;
);