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

74,472

Solution 1

You already gave one answer: you can always just loop over all children and remove them. If you think that you have too many child nodes then maybe you want to replace the svg node by an empty one. If your svg node has some attributes you may use a tag where you place all the child nodes and then just replace the node with an empty one.

Solution 2

If you're using jQuery, you can just do

$("#svgid").empty();

This deletes all child elements of the svg while leaving its other attributes like width and height intact.

Solution 3

Use d3.js. This will remove all contents nodes from svg.

svg.selectAll("*").remove();

Solution 4

I agree to use the clone and replace the element with the cloned one.

Only one line code:

svg.parentNode.replaceChild(svg.cloneNode(false), svg);

Solution 5

I've tried svg.text("") and it seems to work. Clears out all the inner text, keeps the attributes.

Share:
74,472
Aseem Kishore
Author by

Aseem Kishore

Updated on November 20, 2021

Comments

  • Aseem Kishore
    Aseem Kishore over 2 years

    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?