How to access the DOM element that correlates to a D3 SVG object?

Solution 1:

You can also get at the DOM element represented by a selection via selection.node() method

var selection = d3.select(domElement);

// later via the selection you can retrieve the element with .node()
var elt = selection.node();

Solution 2:

Any DOM element in an SVG document will have an ownerSVGElement property that references the SVG document it is in.

D3's selections are just nested arrays with extra methods on them; if you have .select()ed a single DOM element, you can get it with [0][0], for example:

var foo = d3.select(someDOM);

// later, where you don't have someDOM but you do have foo
var someDom = foo[0][0];
var svgRoot = someDom.ownerSVGElement;

Note, however, that if you are using d3.select(this) then this already is the DOM element; you don't need to wrap it in an D3 selection just to unwrap it.

Solution 3:

You can assign IDs and classes to the individual elements if you want when you append:

node.append("circle.bubble")
.attr("r", function(d) { return d.r; })
.style("fill", function(d) { return fill(d.packageName); })
.attr("id", function(d, i) { return ("idlabel_" + i)})
.attr("class", "bubble")
;

And then you can select by class with selectAll("circle.bubble") or select by id and modify attributes like so:

var testCircle = svg.select("#idlabel_3")
.style("stroke-width", 8);