How can I remove or replace SVG content?

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?


Here is the solution:

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

This is a remove function provided by D3.js.


If you want to get rid of all children,

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

will remove all content associated with the svg.


在追加svg元素的时候设置id属性也可以让d3在id元素后面选择这样remove():

var svg = d3.select("theParentElement").append("svg")
.attr("id","the_SVG_ID")
.attr("width",...

...

d3.select("#the_SVG_ID").remove();
链接地址: http://www.djcxy.com/p/60454.html

上一篇: jQuery点击多次触发事件

下一篇: 我如何删除或替换SVG内容?