How can I remove or replace SVG content?

Sami picture Sami · May 28, 2012 · Viewed 218.7k times · Source

I have a piece of JavaScript code which creates (using D3.js) an svg element which contains a chart. I want to update the chart based on new data coming from a web service using AJAX, the problem is that each time I click on the update button, it generates a new svg, so I want to remove the old one or update its content.

Here is a snippet from the JavaScript function where I create the svg:

var svg = d3.select("body")
        .append("svg")
        .attr("width", w)
        .attr("height", h);

How can I remove the old svg element or at least replace its content?

Answer

Sami picture Sami · Jun 6, 2012

Here is the solution:

d3.select("svg").remove();

This is a remove function provided by D3.js.