I have a D3 force directed graph which is first displayed with a few nodes. Each node has a click handler which will expand the graph further and dynamically add more nodes and links to the clicked node. Each node also has a SVG rectangle shape. Because the new links and nodes are added to the existing graph, the links appear on top of the clicked node because SVG is the “painter” model. So I use d3.selectAll().filter().sort() to put the DOM nodes in the correct order. This works except the nodes and links are misplaced on the directed graph. Is there some way to use the sort() but also keep the force.nodes() and force.links() data in sync?
UPDATE: I create a jsfiddle to demonstrate this happening. After a few clicks to create new nodes, the links become unstable. If the call to “reorder_nodes_and_links()” is commented out, the chart is stable but the links are rendered on top of the nodes because of the DOM order.
selection.insert takes a second parameter that tells it to insert things before other things.
I’m having trouble seeing yr fiddle right now, but here’s something from a similar project.
This inserts new lines before anything classed as a node.
https://github.com/mbostock/d3/wiki/Selections#wiki-insert