Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove or replace SVG content?

People also ask

How do I clear svg content?

In order to remove SVG content, you can use the remove() function provided by D3. js. The remove() function is used along with two methods which are also provided by D3.

How to remove svg element from html?

actually if you want to remove elements from svg it would be better to use: svg. selectAll("*"). remove(); . This clear contents of the element even if set svg variable to a grouping element ( g ).

How to clear svg in D3?

It is common to remove the existing Scalable Vector Graphics (SVG) element by calling d3. select('#chart'). remove() , before rendering a new chart.


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.


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();

I had two charts.

<div id="barChart"></div>
<div id="bubbleChart"></div>

This removed all charts.

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

This worked for removing the existing bar chart, but then I couldn't re-add the bar chart after

d3.select("#barChart").remove();

Tried this. It not only let me remove the existing bar chart, but also let me re-add a new bar chart.

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

var svg = d3.select('#barChart')
       .append('svg')
       .attr('width', width + margins.left + margins.right)
       .attr('height', height + margins.top + margins.bottom)
       .append('g')
       .attr('transform', 'translate(' + margins.left + ',' + margins.top + ')');

Not sure if this is the correct way to remove, and re-add a chart in d3. It worked in Chrome, but have not tested in IE.


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


You could also just use jQuery to remove the contents of the div that contains your svg.

$("#container_div_id").html("");

You should use append("svg:svg"), not append("svg") so that D3 makes the element with the correct 'namespace' if you're using xhtml.