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?
转载于:https://stackoverflow.com/questions/10784018/how-can-i-remove-or-replace-svg-content
Here is the solution:
d3.select("svg").remove();
This is a remove
function provided by D3.js.
You should use append("svg:svg")
, not append("svg")
so that D3 makes the element with the correct 'namespace' if you're using xhtml.
You could also just use jQuery to remove the contents of the div that contains your svg.
$("#container_div_id").html("");
I am using the SVG using D3.js and i had the same issue.
I used this code for removing the previous svg but the linear gradient inside SVG were not coming in IE
$("#container_div_id").html("");
then I wrote the below code to resolve the issue
$('container_div_id g').remove();
$('#container_div_id path').remove();
here i am removing the previous g and path inside the SVG, replacing with the new one.
Keeping my linear gradient inside SVG tags in the static content and then I called the above code, This works in IE
Setting the id attribute when appending the svg element can also let d3 select so remove() later on this element by id :
var svg = d3.select("theParentElement").append("svg")
.attr("id","the_SVG_ID")
.attr("width",...
...
d3.select("#the_SVG_ID").remove();
If you want to get rid of all children,
svg.selectAll("*").remove();
will remove all content associated with the svg.
Note: This is recommended in case you want to update chart.