score:7

The index of an element is only well-defined within a collection. When you're selecting just a single element, there's no collection and the notion of an index is not really defined. You could, for example, create a number of g elements and then apply different operations to different (overlapping) subsets. Any individual g element would have several indices, depending on the subset you consider.

In order to do what you're trying to achieve, you would have to keep a reference to the specific selection that you want to use. Having this and something that identifies the element, you can then do something like this.

var value = d3.select(this.parentNode).datum().x;
var index = -1;
selection.each(function(d, i) { if(d.x == value) index = i; });

This relies on having an attribute that uniquely identifies the element.

If you have only one selection, you could simply save the index as another data attribute and access it later.

var gs = d3.selectAll("g").data(data).append("g")
  .each(function(d, i) { d.index = i; });
var something = gs.append(...);
something.each(function() {
  d3.select(this.parentNode).datum().index;
});

Related Query