Languages
[Edit]
EN

JavaScript - how to remove element / node from DOM?

2 points
Created by:
Marcin
15740

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>

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join