Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 append element only if element not exist

I have a problem with D3, if I append an Element a second time I will get duplicate elements in the parent node.

  node.enter().insert("svg:g")
      .attr("class", 'test')
      .attr("width", '63px')
      .attr("height", '68px')
      .call(force.drag);

  node.append("svg:circle")
      .attr("class", "bg-circle")
      .attr("r", "30px");

For Example i will get:

<g class="test">
   <circle class="bg-circle" />
   <circle class="bg-circle" />
</g>

But i want:

<g class="test">
   <circle class="bg-circle" />
</g>

Even when I call my function to set the nodes a second time.

like image 908
Reath Illu Avatar asked Jun 18 '13 13:06

Reath Illu


1 Answers

I had a single function that either initialized or updated a plot, and to prevent duplicate boilerplate from being made while allowing for transitions to the element, I ended up doing the following:

const grid = d3.select('.grid').node()
  ? d3.select('.grid')
  : g.append('g')
      .attr('class', 'grid');
like image 85
duhaime Avatar answered Oct 08 '22 17:10

duhaime