7

I have an svg group upon which I call a drag function.

var container=d3.select("#id");
container.call(dragcontainer);
var dragcontainer = d3.drag()
                        .on("start", function () {})
                        .on("drag", function (d, i) {  
                            //(d3.select(this)).select("rect");
                        })
                        .on("end", function () {});

Apparently, d3.select(this) does not return the container, however they are similar (checked through attributes), but just not exactly the same.

Why does this happen? How can I access container within the called function?

S.Dan
  • 1,826
  • 5
  • 28
  • 55
  • 2
    You could simply access `container` in the closure. – Lars Kotthoff Sep 21 '16 at 04:14
  • What I have here is only a simple scenario, in the actual case, there are multiple containers calling the same drag function and each container has to be passed to another function. – S.Dan Sep 21 '16 at 04:23
  • 1
    Well, `d3.select(this)` should select the container element (although the object itself may not be exactly equal). – Lars Kotthoff Sep 21 '16 at 04:30
  • Is there documentation to see the exact differences between what is returned and the object? – S.Dan Sep 21 '16 at 04:31
  • 2
    `this` is the current DOM element, see https://github.com/d3/d3-drag/blob/master/README.md#drag_on – Lars Kotthoff Sep 21 '16 at 04:32
  • I was doing this sort of comparison and wondered if there was a shorter way. – S.Dan Sep 21 '16 at 04:46
  • http://stackoverflow.com/questions/10337640/how-to-access-the-dom-element-that-correlates-to-a-d3-svg-object – ksav Sep 21 '16 at 09:36
  • @SachDan Perhaps you are getting confused between a d3 selection and its DOM node. Check the console here: https://jsfiddle.net/pbaex8rj/ – ksav Sep 21 '16 at 09:46

1 Answers1

9

Somewhat duplicative of the comments, but the reason is that d3.select returns a d3 selection. Each selection is a different object, even if you select the same DOM node. The following shows the difference:

var container = d3.select("body").node();

var sel1 = d3.select(container);
var sel2 = d3.select(container);

console.log(sel1 === sel2);               // false
console.log(sel1.node() === sel2.node()); // true
Ethan Jewett
  • 6,002
  • 16
  • 25