Tony
Tony

Reputation: 10208

Binding data not working in d3.js

I am trying to generate html using .enter method.

I have the following code:

alert(d3.select(".ul_class").length);
d3.select(".ul_class").data([4, 8, 15]).enter().append("li").text("hello");

The first alert displays "1", so de object is correctly selected. The second line does not append "li" elements inside my DOM object.

What am I doing wrong? Thanks

Upvotes: 4

Views: 1953

Answers (1)

Felix Kling
Felix Kling

Reputation: 816364

You have to create a (empty) selection of li elements first:

d3.select(".ul_class")
  .selectAll('li') // <--
  .data([4, 8, 15]).enter().append("li").text("hello");

Then you bind the data to that empty selection, which will generate placeholders in the selection for the new data.

So you are basically saying:

"Select all li elements and bind the data [4, 8, 15] to them. For all data items that are not bound yet, create a new li element."

DEMO

Upvotes: 8

Related Questions