jQuery Document Operation - replaceWith() Method
Example
Replace each paragraph with bold text:
$(".btn1").click(function() $("p").replaceWith("<b>Hello world!</b>"); });
Definition and usage
The replaceWith() method replaces the selected element with specified HTML content or an element.
Tip:replaceWith() with replaceAll() The same effect. The difference lies in the syntax: the position of content and selector, and replaceAll() cannot use functions for replacement.
Syntax
$().replaceWith(content)
Parameter | Description |
---|---|
content |
Required. Specify the content to replace the selected element. Possible values:
Existing elements will not be moved, but will be copied and wrapped around the selected element. |
Required. Specify the element to be replaced. |
Use a function to replace the element
Use a function to replace the selected element with new content.
Syntax
$().replaceWith(function())
Parameter | Description |
---|---|
function() | Required. A function that returns the new content of the selected element to be replaced. |
More examples
- Use the new element to replace the element
- Use document.createElement() to create a new DOM element, and then use it to replace the selected element.