replaceWith() in javascript

replaceWith() method in javascript

replaceWith() method is used to replace a node or an element with another.

It replaces the whole element.


Try Yourself

Example Explanation

  • In the above example, bold text is created id(id_b).
  • When the button is clicked, javascript function is called.
  • In the function, we are getting the element using its id(document.getElementById("id_b");).
  • Next we are creating a new element(document.createElement("u");), which creates an underlined content.
  • Next we are creating a new element(document.createTextNode("New Content");), which adds content to the newly created element.
  • In next step we are adding the new content to the new element created(new_elem.appendChild(new_content);).
  • And finally we are replacing the old element, with the newly created element(old_elem.replaceWith(new_elem);).