このようなDOM:
<g.module>
<g.control>
<rect>
最も近い API が見つかりませんでした: https://github.com/mbostock/d3/wiki/API-Reference
親から最も近い要素を取得するにはどうすればよいですか? ちょうどこのような:
var module = d3.select(".control").closest(".module");
このようなDOM:
<g.module>
<g.control>
<rect>
最も近い API が見つかりませんでした: https://github.com/mbostock/d3/wiki/API-Reference
親から最も近い要素を取得するにはどうすればよいですか? ちょうどこのような:
var module = d3.select(".control").closest(".module");
次のように、d3 選択プロトタイプに「最も近い」を追加できます。
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);
}
ブラウザーはDOM ノードで最も近いメソッドを使用できるようになりました:
d3.select(rect.node().closest('svg'));
このメソッドを使用した @JayB と同様のコード:
d3.selection.prototype.closest = function(selector) {
var arr = [];
return this.each(function() {
arr.push(this.closest(selector));
});
return d3.selectAll(arr);
};
それはちょうど使用することを許可します:rect.closest('svg');
唯一の問題は、IE でサポートされていないことです。