Reputation: 43
var dataArray=[20,40,50,60,70,80,90];
d3.select("body")
.selectAll(".small-div")
.data(dataArray)
.enter()
.append("span")
.text(function(d){
return d;
});
<script src="https://d3js.org/d3.v4.min.js"></script>
I have created the above set of code to add the data array to the div elements with class="small-div". The code is not working, please give any solution
Upvotes: 2
Views: 537
Reputation: 102219
Your problem is just this line:
.enter()
In D3, this is one of the most famous methods. It...
Returns the enter selection: placeholder nodes for each datum that had no corresponding DOM element in the selection. (emphasis mine)
So, if you already have the <div>
s in the page, your "enter" selection will be empty!
Let's prove it:
var dataArray = [20, 40, 50, 60, 70, 80, 90];
var selection = d3.select("body")
.selectAll(".small-div")
.data(dataArray)
.enter();
//nothing will be appended here!
selection.append("span")
.text(function(d) {
return d;
});
console.log("the size of the enter selection is: " + selection.size())
<script src="https://d3js.org/d3.v4.min.js"></script>
<div class="small-div"></div>
<div class="small-div"></div>
<div class="small-div"></div>
<div class="small-div"></div>
<div class="small-div"></div>
<div class="small-div"></div>
<div class="small-div"></div>
As you can see, nothing happens, no element is appended (and the message in the console is pretty clear).
However, if we simply drop the enter()
, the data will be bound to the existing DOM elements, and you'll have what we call an "update" selection. Now you're appending the <span>
elements to a selection which is not empty.
Have a look:
var dataArray = [20, 40, 50, 60, 70, 80, 90];
d3.select("body")
.selectAll(".small-div")
.data(dataArray)
.append("span")
.text(function(d) {
return d;
});
<script src="https://d3js.org/d3.v4.min.js"></script>
<div class="small-div"></div>
<div class="small-div"></div>
<div class="small-div"></div>
<div class="small-div"></div>
<div class="small-div"></div>
<div class="small-div"></div>
<div class="small-div"></div>
Upvotes: 2