Remove DOM Element in JavaScript

- 1 minute read

This simple JavaScript snippet will grab an element from the page and delete it:

const deleteElement = (id) => {
    document.getElementById(id).remove();
};

Suppose we had an element like this:

<div id="box"></div>

We could remove it from the page like this:

deleteElement(`box`);

But this snippet isn’t very flexible. We might not always want to delete an element just based on an ID selector.

Here is an improved deleteElement function with support for deleting by class name and tag name, not just ID:

const deleteElement = (query) => {
    if (typeof query === `string`) {
        if (query.length > 0) {
            query[0] === `#`
                ? document.querySelector(query).remove();
                : document.querySelectorAll(query).forEach((el) => el.remove());
        }
    }
};

// Delete by ID:
deleteElement(`#box`);

// Delete by class name:
deleteElement(`.box`);

// Delete by tag name:
deleteElement(`div`);

Link to this section Conclusion

And that’s how you can nuke elements from the DOM using JavaScript. Have fun!