Languages
[Edit]
EN

JavaScript - remove element from DOM

5 points
Created by:
Nathanial-Donald
554

In this artcle, we would like to show how to remove some Element or Node from DOM using JavaScript.

Quick solution:

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

element.remove();

Hint: element remove() method was introduced in the major web browsers around 2013-2015.

 

Practical examples

In this section you can find different methods that let's to remove Node from DOM. In DOM Nodes are: Element, Text, Comment. For more details check out this article.

 

removeChild() method example

This approach works in older web browsers.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="element">Some text here ...</div>
  <button onclick="removeText()">Remove text</button>
  <script>

    function removeNode(element) {
        var parent = element.parentNode;
        if (parent) {
            parent.removeChild(element);
        }
    }


    // Usage example:

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

    function removeText() {
        removeNode(element);
    }

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

 

remove() method example

This approach is not supported by older web browsers (before 2013-2015).

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="element">Some text here ...</div>
  <button onclick="removeText()">Remove text</button>
  <script>

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

    function removeText() {
        element.remove();
    }

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

 

Referneces

  1. Element remove() method - MDN Docs

  2. Node removeChild() method - MDM docs

Alternative titles

  1. JavaScript - remove node from DOM
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