wootscootinboogie wootscootinboogie - 3 months ago 19
Javascript Question

d3.js 4.2 first element in selection not binding

Simple question for someone checking out d3 4:
https://jsfiddle.net/dwrzso58/

d3.select("body")
.data([1,2,3])
.enter()
.append("div")
.text((d,i)=>d)


when this code runs only 2 and 3 show up in the DOM. What gives with the first element in the array being lost?

Answer

d3.select("body") selection contains one element so the .data() adds 1 to the selected body element and 2, 3 are left over and included into the .enter() pipeline. If you want to enter all three elements you have to call .data() on an empty selection like this:

d3.select("body").select("div")
.data([1,2,3])
.enter()
.append("div")
.text((d,i)=>d)