JSFiddle - React, Tailwind, and code Playground
by Nivaldo
HTML
<button id="update">Update</button>
<div id='myDiv'></div>
JavaScript
var data = [1,2,3,4,5,6,7,8,9,10];
var newData = [2,3,4,6,7,8];
var dataMap = {
1 : 'a',
2 : 'b',
3 : 'c',
4 : 'd',
5 : 'e',
6 : 'f',
7 : 'g',
8 : 'h',
9 : 'i',
10 : 'j'
}
//console.log(dataMap);
function update(dataset) {
var root = d3.select('#myDiv')
.selectAll('div')
.data(dataset, function(d){return d;});
// enter selection
root
.enter()
.append('div');
// update selection
root
.text(function(d){ return dataMap[d] });
// capturing the exit selection
var rootExit = root.exit();
// using the exit selection before removal
// i.e. printing exiting div text to console
rootExit.each(function(d){ console.log(d3.select(this).text()) });
// finally removing elements
rootExit
.remove();
};
update(data);
function updateData() {
update(newData);
};
d3.select("#update")
.on("click",updateData);