How to remove all elements inside an element?

I seek a swift and sound way to remove all elements inside an element.
I tried this which failed:

document.querySelector("#content").document.querySelectorAll("*").remove();

I just want to remove all elements inside the element with the CSS ID #content.

    let element = document.querySelector('#content');
    while (element.firstChild) {
        element.removeChild(element.firstChild);
    }
1 Like

I don’t know if there are drawbacks to the following approach, but it seems to do the trick.

const content = document.querySelector('#content')
const clone = content.cloneNode() // clones without children
content.replaceWith(clone)

MDN - cloneNode
MDN - replaceWith

1 Like

I usually use

document.getElementById('content').innerHTML = "";
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.