简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM