Languages
[Edit]
EN

JavaScript - replace DOM element with new one

3 points
Created by:
James-Z
767

In this article, we're going to have a look at how to dynamically replace DOM element in JavaScript.

Simple overview:

oldElement.parentNode.replaceChild(newElement, oldElement);

Note: it is good to check before that parent node exists - old element is inside some element.

There are 2 simple ways how to do it:

  • directly with replaceChild method,
  • with insertBefore and removeChild methods.

Look on the below code too see practical example.

1. replaceChild method example

Solution presented in this section checks that parent element for replaced element exists before replace operation is completed.

// ONLINE-RUNNER:browser;

<!doctype>
<html>
<body>
  <div id="element">Old element here...</div>
  <script>

    function replaceElement(oldElement, newElement) {
        var parent = oldElement.parentNode;
        if (parent == null) {
            throw new Error('Old element does not have parent.');
        }
        parent.replaceChild(newElement, oldElement);
    }

    var oldElement = document.querySelector('#element');
    var newElement = document.createElement('div');
    newElement.innerHTML = 'Now new element is here...';

    replaceElement(oldElement, newElement );

  </script>
</body>
</html>

2. Custom method example

Solution presented in this section checks that parent element for replaced element exists before replace operation is completed. To replace element two methods were used: insertBefore and removeChild.

// ONLINE-RUNNER:browser;

<!doctype>
<html>
<body>
  <div id="element">Old element here...</div>
  <script>

    function replaceElement(oldElement, newElement) {
        var parent = oldElement.parentNode;
        if (parent == null) {
            throw new Error('Old element does not have parent.');
        }
        parent.insertBefore(newElement, oldElement);
        parent.removeChild(oldElement);
    }

    var oldElement = document.querySelector('#element');
    var newElement = document.createElement('div');
    newElement.innerHTML = 'Now new element is here...';

    replaceElement(oldElement, newElement );

  </script>
</body>
</html>
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join