DOM like this:
<g.module>
<g.control>
<rect>
I didn't find the closest API: https://github.com/mbostock/d3/wiki/API-Reference
How can I get the nearest matched elements from it's parent? Just like this:
var module = d3.select(".control").closest(".module");
If your DOM is really that specific example, you can select parent nodes with D3 as noted in their docs here:
You can see the parent node of each group by inspecting the parentNode property of each group array, such as selection[0].parentNode.
So in your case, var module = d3.select(".control").parentNode;
should work.
Browsers now have closest method on DOM node:
d3.select(rect.node().closest('svg'));
and similar code to @JayB with this method:
d3.selection.prototype.closest = function(selector) {
var arr = [];
this.each(function() {
arr.push(this.closest(selector));
});
return d3.selectAll(arr);
};
that allow to use just: rect.closest('svg');
the only problem is that it's not supported by IE
You could add "closest" to the d3 selection prototype like this:
d3.selection.prototype.closest = function(selector){
var closestMatch = undefined;
var matchArr = [];
this.each(function(){
var elm = this;
while(typeof elm.parentNode.matches === "function" && !closestMatch){
elm = elm.parentNode;
if(elm.matches(selector)){
closestMatch = elm;
matchArr.push(closestMatch);
}
}
closestMatch = undefined;
});
return d3.selectAll(matchArr);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With