VPel
VPel

Reputation: 413

D3 Getting Name Of Parent Node

I have a node-link diagram drawn in D3 via a JSON document. Example below.

enter image description here

What I want to do is get the parent node's name when a child is clicked on. For example, if I click on "Red", I want "Color" to get returned.

All the things I've tried using .parent have been failures. In my debugging so far, I've tried this, this.parent and this.parent.parent... but none of them give me what I'm looking for, nor can I see how I could get this data.

I can post the code or data or whatever you guys need, but I'm guessing I'm missing something small and trivial and hoping you can help.

Upvotes: 3

Views: 3362

Answers (1)

nrabinowitz
nrabinowitz

Reputation: 55688

It sounds like you're trying to get the parent from this, which in most D3 callbacks refers to the associate DOM element. You want the actual node data, which will be passed in as the first argument:

node.append("circle")
  .on('click', function(node) {
      alert(node.parent.name);
  });

See http://jsfiddle.net/nrabinowitz/wxW3q/

Upvotes: 4

Related Questions