Languages
[Edit]
EN

JavaScript - how to remove element / node from DOM?

2 points
Created by:
Marcin
2450

Using JavaScript it is possible to remove element in following ways.

1. removeChild method example

// ONLINE-RUNNER:browser;

<!doctype 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:

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

    function removeText() {
        removeNode(element);
    }

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

2. remove() method example

This approach is not supported by older browsers.

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

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists 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.