Ian
Ian

Reputation: 13852

Getting d3.js data from html

I'm new to d3.js and trying to understand how to retrieve elements that are already on an html page.

If I try something like the following, 'd' is undefined when I look in the console log. I can access some of the td information via the 'this' keyword, but looking at the d3 API https://github.com/mbostock/d3/wiki/Selections#wiki-style, it says if style takes a value as a function, it passes the current 'datum' and index.

I can get the index fine, but datum is always undefined. Is there something obvious I'm missing to retrieve the values, or have the wrong way around ?

<table class="results">
<tr><td>13/1/0014</td><td>81</td><td>3</td><td></td></tr>
<tr><td>12/1/0014</td><td>690</td><td>47</td><td></td></tr>
<tr><td>5/1/0014</td><td>450</td><td>26</td><td></td></tr>
</table>

d3.selectAll(".results td:nth-child(4n+2)")
  .style("background-color", function(d) { 
         console.log( d );

         //change style depending on d, but d is always undefined
         //I can access the elements via this, but not d ? 

});

jsfiddle http://jsfiddle.net/a5WkH/2/

Upvotes: 2

Views: 1902

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109242

D3 assumes that you bind data to the elements using .data() or .datum(). If you haven't done that, something like function(d) { ... } won't work. Technically what happens is that D3 adds the data bound to a DOM element as the .__data__ attribute to that element. So if you really don't want to use .data() or .datum(), you could do something like this.

d3.selectAll(".results").each(function() { this.__data__ = d3.select(this).text(); });

This is what I have done here. It is usually better to use .data() though.

Upvotes: 2

Related Questions