Table of Contents
HTMLElement interface suffice.
These elements have properties and methods, and one such methods is the
replaceWith method. The
replaceWith method allows us to replace the element it’s called upon in the children list of its parent with a set of
String objects (or equivalent
replaceWith method and uses it for DOM manipulation.
replacewith method to manipulate DOM
With a typical syntax structure as below, the
replacewith method allows us to replace elements by directly referencing the child nodes where
Element is the element/node to be replaced and the
Node is the element/node that will replace the element/node.
Element.replacewith(Node); Element.replacewith(Node1, Node2);
Also, you can replace it with multiple elements/nodes.
replacewith method, we will display paragraph text and change the text using the method. All the HTML and JS will be written together using the
After we click the button to trigger the
replacewith method, we have the below image.
In the HTML code, we added the
btn id (identifier) to the
paragraph tag by using the
querySelector method and bind it to
pTag binding. Afterward, we can create a new element (
newNode) that will replace the referenced element and bind a value to it. Finally, we make use of the
replacewith method on
pTag (the referenced value) and
newNode (the new node).
Also, we can add multiple nodes by adding new elements or nodes to the arguments of the
replacewith method. To do such, we can replace the code with the
replacewith method expression below. We can also create new elements too.
pTag.replaceWith(newNode, "added node text");
replacewith method, we need to reference the element/node that we want changed and add the new element/node as an argument. Also, we can add multiple nodes or elements via the