Deleting and recreating visual elements on any change is expensive. That is one reason why D3 provides the Enter – Update – Exit pattern. As you have already heard D3 provides the method enter(), and there is also the exit()-function. Both control the interaction between data and HTML elements it is bound to.
Let's recap:
To see how the enter update exit pattern works, we now want to color all fruits green, which are new, and all updated ones red. All exit-elements should be removed. Then we want to merge the enter and update elements and add them a black border.
First we have to select the fruits from before and bind the new data to it. Here it is very important that we set a key as second parameter, which D3 needs to identify and compare the objects.
let fruitsUpdate = diagram.selectAll("circle")
.data(newData, d => d.name)
Then we have to define the enter, merge and exit selections.
let fruitsEnter = fruitsUpdate.enter()
.append("circle")
let fruitsMerge = fruitsUpdate.merge(fruitsEnter)
let fruitsExit = fruitsUpdate.exit()
And then we can add all the changes for the elements:
fruitsEnter
.attr("fill","green")
fruitsMerge
.attr("cy",100)
.attr("cx",(d,i) => scaleX(d.weight))
.attr("r", d => d.size)
.attr("stroke-width","2")
.attr("stroke","black")
.on("mouseover",fruitOver)
.on("mouseout",fruitOut)
fruitsUpdate
.attr("fill","red")
fruitsExit.remove();
So now take a look at what happens, when you change the data: