Enter, Update, Exit
Christian Behrens
15911

Ok, so from what I can understand from the documentation the reason it’s not working with existing SVG elements declared via HTML is that you need to pass a key function for D3 to be able to reference the object. If you don’t pass the key function then it doesn’t work. However when you iterate over the selection without making it part of the enter() it does seem to work.

So for it to work in your example you need to add a key function.

# selection.data([values[, key]])

so instead of:

var selection = d3.select(“#chart”)
 .selectAll(“.bar”).data(numbers);

you should have:

var selection = d3.select(“#chart”)
 .selectAll(“.bar”).data(numbers, function(d) { return d; });

This presumably gives creates a reference to the existing SVG elements. Doing so allows this code to work:

selection.enter()
 .append(“div”).attr(“class”, “bar”)
 .style(“margin-top”, function(d){ 
 return (100 — d) + “px”; 
 }).style(“height”, function(d){ 
 return d + “px”; 
 }).on(“click”, function(e, i){
 numbers.splice(i, 1);
 update();
 });
 selection.exit().remove();
};
update();

Which wasn’t working on the existing SVG elements.