Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❀ đŸ’»
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

JavaScript - replace DOM element with new one

0 contributions
3 points

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>
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more