D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
denisemauldin
Full window
Github gist
Use g containers with elements inside
<!DOCTYPE html> <meta charset="utf-8"> <html> <head> <script src="https://d3js.org/d3.v4.min.js"></script> <style> #svg1 { border: thin solid red; } .circles { fill: red; } </style> </head> <body> <svg id="svg1" width="60" height="60"></svg> <button id="update" type="text/button">Update</button> <button id="reset" type="text/button">Reset</button> <script> let inputData = [ { id: 1, x: 10, y: 10 }, { id: 2, x: 30, y: 30 }, { id: 3, x: 50, y: 50 }, ]; function join1(data) { // select the container elements let containers = d3.select("#svg1") .selectAll('.container') .data(data); // select entering elements and append a g element let enterSel = containers.enter() .append("g") .attr("class", "container"); // select exiting elements let exitSel = containers.exit(); // select elements that remain let mergeSel = containers.merge(enterSel); // add a text label to each container enterSel.append("text").attr("text", "label"); // add a circle to each container let circlesEnter = enterSel.append("circle"); // add styles and data to new and remaining elements let circlesMerge = mergeSel .select("circle") .attr("class", "circles") .attr("r", d => 10) .attr("cx", d => d.x) .attr("cy", d => d.y); // remove exiting elements exitSel.remove(); } join1(inputData); d3.select("#reset").on("click", function() { d3.select("#svg1").selectAll("g").remove(); inputData = [ { id: 1, x: 10, y: 10 }, { id: 2, x: 30, y: 30 }, { id: 3, x: 50, y: 50 }, ]; join1(inputData); }); d3.select("#update").on("click", function() { inputData = [ { id: 1, x: 10, y: 10 }, { id: 2, x: 40, y: 40 }, { id: 3, x: 10, y: 50 }, { id: 4, x: 50, y: 10 }, ]; join1(inputData); }); </script> </body> </html>
https://d3js.org/d3.v4.min.js