tic
tic

Reputation: 4189

removing all svg elements in D3 save some specified

const svg=d3.append("svg").attr(...)
const g1=svg.append("g").attr("id","g1").attr(...)
var v1=g1.append(...)
... // many other nested append operations 
const g2=g1.append("g").attr("id","g2").attr(...)
var v2=g2.append(...)
... // many other nested append operations

Then how can I remove all elements from svg object apart groups g1 and g2? Something similar to:

svg.selectAll("*:not('#g1'):not('#g2')").remove();

that does not work.

Upvotes: 0

Views: 90

Answers (1)

matthias.rocks
matthias.rocks

Reputation: 625

I would apply a class to all elements that you want to keep, e.g.:

const svg=d3.append("svg")
  .attr(...)

const g1=svg.append("g")
  .attr(...)
  .classed('doKeep', true)

var v1=g1.append(...)

// After adding many nested elements to g1
g1.selectAll('*')
  .classed('doKeep', true)

...

const g2=g1.append("g")
  .attr(...)
  .classed('doKeep', true)

var v2=g2.append(...)
...

// After adding many nested elements to g1
g2.selectAll('*')
  .classed('doKeep', true)

Then you can select all elements in you SVG that do not have that class, with a :not() CSS selector as such:

svg.selectAll(':not(.doKeep)').remove()

The inverse would also work, where you mark all elements you want to delete, and then delete them after selecting them. But giving the phrasing of your question, this is the most accurate approach.

Hope this helps!

Edit: Updated to reflect updated question that specifies many nested elements.

Upvotes: 1

Related Questions