Mkni1408
Mkni1408

Reputation: 125

Deleting d3 svg elements for redraw

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!

Upvotes: 3

Views: 24656

Answers (2)

KateJean
KateJean

Reputation: 428

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

Upvotes: 9

FernOfTheAndes
FernOfTheAndes

Reputation: 5015

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");
}

Upvotes: 6

Related Questions