/

How to Replace a DOM Element

How to Replace a DOM Element

Replacing a DOM element with another might be necessary in certain situations. If you have a DOM element and want to replace it with a different one, there are a couple of methods you can use.

The first method is to use the replaceWith() method. This method is available on DOM elements and allows you to replace the element with another one. Here is an example:

1
2
3
4
const el1 = document.querySelector(/* ... */);
const el2 = document.querySelector(/* ... */);

el1.replaceWith(el2);

It’s important to note that this method is not supported on older browsers such as Edge <17 and IE11. If you need to support these browsers, you should transpile your code to ES5 using Babel or consider using an alternative method.

The second method is to use the replaceChild() method. This method is supported by all browsers, making it a reliable solution for replacing DOM elements. Here is an example:

1
2
3
4
const el1 = document.querySelector(/* ... */);
const el2 = document.querySelector(/* ... */);

el1.parentNode.replaceChild(el2, el1);

Using the parentNode property, you can access the parent of the element and then use replaceChild() to replace the target element with the new one.

By following these approaches, you can easily replace a DOM element with another one, depending on your specific requirements.

tags: [“JavaScript”, “DOM manipulation”, “replace DOM element”]