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

﹥>﹥吖頭↗ 提交于 2019-11-28 19:04:44

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();

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.

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!