Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does d3 have api which similar with jQuery.closest(selector)?

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");
like image 259
Kris Zhang Avatar asked Aug 22 '13 08:08

Kris Zhang


3 Answers

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.

like image 61
edhenn Avatar answered Oct 13 '22 12:10

edhenn


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

like image 44
jcubic Avatar answered Oct 13 '22 12:10

jcubic


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);
        }
like image 31
JayB Avatar answered Oct 13 '22 12:10

JayB