Languages
[Edit]
EN

JavaScript - replace DOM element with new one

3 points
Created by:
Marcin
2462

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>
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.