Deleting d3 svg elements for redraw

21,547

Solution 1

FIDDLE with a quick example of adding, removing and the adding again an SVG and a contained circle. Hope this helps.

function update() {
    svg.remove();
    svg = d3.selectAll("body").append("svg");
    svg.append("circle")
        .attr("cx",40)
        .attr("cy",40)
        .attr("r",20)
        .style("fill","blue");
}

Solution 2

I had a similar problem to this. removing the SVG element did not allow me to fully update the data like I wanted.

Instead, I removed the g elements created inside the SVG with this line:

d3.selectAll("g > *").remove()

in my updateGraph() function

Full explanation and situation shown here: Repainting/Refreshing Graph in D3

Share:
21,547
Mkni1408
Author by

Mkni1408

Updated on July 09, 2022

Comments

  • Mkni1408
    Mkni1408 almost 2 years

    I hope you can help me, because this is driving me nuts!

    So i was trying to redraw a svg using d3. In my code i add the svg using:

    d3.xml("Images/vertical_line.svg", "image/svg+xml", function(xml) {
    
      var importedNode = document.importNode(xml.documentElement, true);
      var svg = d3.select('#'+id+'_verticallinecontainer').node().appendChild(importedNode);
    
      });
    

    When my update function is called i then proceed to remove the element:

    d3.select("#"+id+'_verticallinecontainer').remove();
    

    This removes the container and the element. I then proceed with redrawing the svg again using the above code.

    My problem is that when it appends the svg again it does it twice and i do not understand why! It seems that d3 somehow caches the svg, adding it again.

    Hope you can help to clear out what is wrong, any help would be appreciated!