Languages
[Edit]
EN

JavaScript - replace DOM element with new one

3 points
Created by:
Marcin
15680

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>
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

â€ïžđŸ’» 🙂

Join