简体   繁体   中英

How to add back to DOM an existing D3 SVG chart?

Hi have a D3 SVG object:

 d3.select("#chart").append("svg")
.attr('id', 'chartId' + idx)

To which I append rects to create a bar chart.

I would like to be able to add and remove it from the DOM.

I am able to remove it easily with:

d3.select('svg#chartId' + j).remove();

How can I re-append the entire SVG chart I just removed?

D3 doesn't support reattaching nodes that have been deleted.

selection.remove() doesn't completely destroy the node though, it acts quite similarly to jQuery's detach() method. (Using jQuery with SVG elements never ends well)

The good news is that this is pretty easy with the built-in SVG DOM.

// .remove() returns the detached node.
var el = d3.select('.selection').remove();
var nativeEl = el[0][0];
nativeEl.parentNode.appendChild(nativeEl);

Usually it would probably just be easier to show and hide these elements, but in cases like re-arranging the order of elements post-render, this can be pretty useful.

Use detach() instead of remove()

var refToElelment = $(d3.select('svg#chartId' + j)).detach();

OR

$('#chartId' + j).detach()

Later..

$('#target').append(refToElelment);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM