Languages
[Edit]
EN

JavaScript - remove DOM element

4 points
Created by:
Brandy-Mccabe
724

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

Simple overview:

// not supported by older browsers (not supported in all IE versions)
element.remove();

// works for older browsers too
element.parentNode.removeChild(element);

Note: it is good to check that parent node exists - element is placed in other element.

There are 2 simple ways how to do it:

  • directly with remove method,
  • with removeChild method.

Look on the below code too see practical example.

1. remove method example

Solution presented in this section remove element with one methof call (remove method).

Note: not supported by older browsers (not supported in all IE versions)

// ONLINE-RUNNER:browser;

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

    var element = document.querySelector('#element');
    element.remove();

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

2. Custom method example

Solution presented in this section checks that parent element (for removed element) exists and remove the element from it.

// ONLINE-RUNNER:browser;

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

    function removeElement(element) {
        var parent = element.parentNode;
        if (parent == null) {
            throw new Error('Element does not have parent.');
        }
        parent.removeChild(element);
    }

    var element = document.querySelector('#element');
    removeElement(element );

  </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