jQuery Replace All: Main Tips
- The jQuery
.replaceAll()
inserts new HTML content instead of the specified elements. - This function differs from .replaceWith() (also used to make jQuery replace elements) in its syntax.
Usage of .replaceAll()
jQuery .replaceAll()
replaces targeted elements with new HTML content. In the example provided you can see all <h2>
elements replaced by <h1>
:
Example
$("button").click(() => {
$("<h1>Hello World!</h1>").replaceAll("h2");
});
Follow this syntax to replace jQuery elements with new content:
$(content).replaceAll(target);
The jQuery replace all elements method accepts two arguments:
content
specifies the HTML elements to insert instead of the selected ones.target
defines the content to be replaced.
Note: when you remove the old nodes and replace them with new ones using jQuery replace all method, all their event handlers and data are removed as well.