Languages
[Edit]
EN

JavaScript - remove DOM element

4 points
Created by:
JustMike
3584

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>
Hey ūüĎč
Would you like to know what we do?
  • Dirask is online IT community for professionals and hobbyist 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.