🔥 $100K Hit! Where Will Bitcoin Go Next? Find Out Live!

Code has been added to clipboard!

Make jQuery Replace All Elements With New HTML Content

Reading time 1 min
Published Jan 23, 2018
Updated Oct 1, 2019

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.