Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.js: how to traverse back up the DOM

I'm not quite sure which aspect(s) of javascript, the DOM or d3.js this exposes my lack of knowledge of: just know that I am sorry to be asking such a basic question as the following. I'm new here.

I have a json like this:

[{"link":"a", "count": 3}, {"link":"b", "count": 4}, {"link":"c", "count": 2}]

and I'd like to make something that looks like

<ul>
    <li> <a>a</a> (3)</li>
    <li> <a>b</a> (4)</li>
    <li> <a>c</a> (2)</li>
</ul>

using d3.js (to address the obvious: I want to do a LOT more with d3, this just captures a problem I have).

After popping a <ul> tag in my html, somewhere in a callback from d3.json I can write something like this:

d3.select("ul")
    .selectAll("li")
    .data(json)
    .enter()
    .append("li")
    .append("a")
    .text(function(d){return d.link})

(though this is untested! how do javascript people test little scraps of code?). This will (probably) give me

<ul>
    <li><a>a</a></li>
    <li><a>b</a></li>
    <li><a>c</a></li>
</ul>

but now I can't get out of the <a> tag! I can't figure out what ungodly combination of this and selecting parents or whatnot I need to do to tack on that extra piece of information before the close of the list item tag. What do I need to do?

like image 385
Mike Dewar Avatar asked Oct 06 '11 08:10

Mike Dewar


1 Answers

Simple: don't go overboard with method chaining. :)

var ul = d3.select("ul");

var li = ul.selectAll("li")
    .data(json)
  .enter().append("li");

var a = li.append("a")
    .text(function(d) { return d.link; });

Now you can add other stuff to the li. In this case, since D3 only lets you add elements (rather than raw text nodes), you'll probably want to add a span for the parenthetical text:

li.append("span")
    .text(function(d) { return " (" + d.count + ")"; });
like image 165
mbostock Avatar answered Nov 03 '22 14:11

mbostock