Ionică Bizău
Ionică Bizău

Reputation: 113475

How can I get the dom svg element from d3 node data?

I have nodes variable that is an array with all nodes from graph. Each node has a SVG g (group) SVG element in DOM.

To select the data having the DOM element I do d3.select(myElement).data()[0], but how can I get the DOM element having the data?

Upvotes: 2

Views: 1499

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109282

You can do this using D3's data matching. The idea is to have the data "identify" the correct element for you.

d3.selectAll("allMyElements").data([datumIwantElementFor], suitableKeyFunction);

Complete demo here.

To be clear, I do not recommend taking this approach. This is prone to breaking when you add more elements to the document and accidentally select some of those, use the same data in more than one place, or change the data format. It will lead to bugs that are really hard to spot unless you know what you're looking for.

A better approach is to assign an ID or class from that data to each element that you bind the data to so that you can select it directly when you have the data. This will also be more efficient.

Upvotes: 3

Related Questions