Remove a DOM Element

Summary: in this tutorial, you’ll learn how to remove an element from the DOM using the removeChild() and remove() method.

Removing an element using the removeChild() method

To remove an element from the DOM, you follow these steps:

  • First, select the target element that you want to remove using DOM methods such as querySelector().
  • Then, select the parent element of the target element and use the removeChild() method.

Suppose that you have the following HTML document:

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Removing a element</title>
    </head>

    <body>
        <ul>
            <li><a href="/home">Home</a></li>
            <li><a href="/service">Service</a></li>
            <li><a href="/about">About</a></li>
        </ul>
        <script>
            // select the target element
            const e = document.querySelector("li:last-child");
            // remove the last list item
            e.parentElement.removeChild(e);
        </script>

    </body>

</html>Code language: HTML, XML (xml)

How it works:

  • First, select the last list item using the querySelector() method.
  • Then, select the parent element of the list item using the parentElement and call the removeChild() method on the parent element to remove the last list item.

Note that if you just want to hide the element, you can use the style object:

const e = document.querySelector('li:last-child');
e.style.display = 'none';Code language: JavaScript (javascript)

Removing an element using the remove() method

To remove an element from the DOM, you can also use the remove() method of the element.

All major browsers support the remove() method except for IE. Since IE was deprecated, you can use the remove() method today. For example:

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Removing a element</title>
    </head>

    <body>
        <ul>
            <li><a href="/home">Home</a></li>
            <li><a href="/service">Service</a></li>
            <li><a href="/about">About</a></li>
        </ul>
        <script>
            // select the target element
            const e = document.querySelector("li:last-child");
            // remove the last list item
            e.remove();
        </script>

    </body>

</html>Code language: HTML, XML (xml)

How it works.

  • First, select the last element of the ul element.
  • Second, call the remove() of that element to remove it from the DOM.

Summary

  • Use the removeChild() or remove() method to remove an element from the DOM.
  • Set the style.display of the element to 'none' to hide the element.
Was this tutorial helpful ?