const scores = [ { name: "Alice", score: 96 }, { name: "Billy", score: 83 }, { name: "Cindy", score: 81 }, { name: "David", score: 96 }, { name: "Emily", score: 88 } ]; /** * @see https://bost.ocks.org/mike/join/ */ const update = d3.select('.chart') .selectAll('div') // A "data join": merge the data with that selection. .data(scores, function (d) { return d ? d.name : this.innerText; }) // Initially (empty div), 5 elements in Enter, 0 in update, 0 in exit. // Returns the update selection by default. // When we add divs for Billy and Cindy, they are already mapped, so won't get // text added and color set at the next step, (by default), so we set them now: // they are UPDATED, while... .style('color', 'blue'); // access the Enter selection const enter = update.enter() // Append a div for everything in the data which doesn't already have a DOM element. // ...Alicy, David and Emily are being created (appended) .append('div') // create the divs // populate them. The function receives each data element as its first argument. // D3 convention: "d" is the name for the data element. .text(d => d.name) .style('color', 'green') update.exit() // access the Exit selection .remove(); update.merge(enter) .style('width', d => d.score + 'px') .style('height', '50px') .style('background-color', 'lightgreen') .style('border', '1px solid black');