//Array with 4 objects var dataArray = [ {value : 'one', color:'red', width: 100}, {value: 'two', color:'green', width: 200}, {value: 'three', color:'blue', width: 150}, {value: 'four', color:'yellow', width: 300} ]; function render(data) { //First use data function and pass data var updateDivSelection = d3.select('body').selectAll('div'). data(data); //Not calling style function here //Use enter to append the divs var enterDivSelection = updateDivSelection.enter(). append('div'). text(function(d) { return d.value }); //for inner text //Not calling style function here as well //Use updateDivSelection now, which holds collection of both newly added and updated divs and call style on it updateDivSelection. style({ 'background-color': function(d){ return d.color }, 'width': function(d){ return d.width + 'px' } }); //Using exit to remove extra divs updateDivSelection.exit().remove(); } //Calling render function and passing the data render(dataArray); //Updating data after 1 sec and calling render again setTimeout(function() { //update first object width dataArray[0].width = '400'; //call render again render(dataArray); },1000);
<!-- no div elements initially --> <body> </body