Is there an easy way to clear an SVG element's contents?

Viewed 77520

In HTML, I can clear a <div> element with this command:

div.innerHTML = "";

Is there an equivalent if I have an <svg> element? I can't find an innerHTML nor innerXML or even innerSVG method.

I know the SVG DOM is a superset of the XML DOM, so I know I can do something like this:

while (svg.lastChild) {
    svg.removeChild(svg.lastChild);
}

But this is both tedious and slow. Is there a faster or easier way to clear an SVG element?

10 Answers

If you want to keep defs of your svg as me use this

function clear(prnt){
    let children = prnt.children;
    for (let i=0;i<children.length;){
        let el = children[i];
        if (el.tagName!=='defs'){
            el.remove();
        }else(i++);
    }
}

No need to loop, just assign an empty string

svg.innerHTML = "";
Related