Top community members

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

[Edit]
EN

JavaScript - remove DOM element

4 points
Created by:
JustMike
3364

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>

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