Accepted answer

You need an "enter", "exit" and "update" selections.

First, we bind the data (with a key function):

elementGroup = circlesGroup
    .data(dataset, function(d){ return d.unique_followers});

Then, we set the enter selection:

var elementEnter = elementGroup.enter()

Now an important note: as this is D3 v4.x, you need to merge the selections to have a working update selection:

elementEnter.merge(elementGroup).attr("transform", function(d,i){
    return "translate(" + (i*80+45) + "," + h/2 + ")"; 

Finally, the exit selection:

var elementExit = elementGroup.exit().remove();

Here is your CodePen:


In my case I had svg circles and had to .remove() them and add completely new ones with the same class. But on d3.selectAll(".dynamic_child).on("click"... didn't register it. I found a workaround that doesn't dive deep into d3.js and instead uses jQuery.

My solution is the following:

$( ".static_parent" ).on("click", '.dynamic_child', function(){
    console.log("I'm working!")

where the static_parent is just parent div that you keep and the dynamic_child is element(s) (html or svg) that you remove and add on the fly.

Original source post

Related Query