Get one element from d3js selection, by index

The most natural way to manipulate just one element is using the filter function:

var data = [[0,0,2],[0,23,5],[2,12,5]];
var circleSet = svg.selectAll()
         .data(data)
         .enter()
         .append('circle');
var filteredCircleSet = circleSet
         .filter(function (d, i) { return i === 1;})
         // put all your operations on the second element, e.g.
         .append('h1').text('foo');    

Note that depending on what you do with the other elements you might use one of the two variants of this approach:

  • variant a): use the filter in the data function (to reduce the data and the appended elements)

  • variant b): use the filter to exclude instead of to include in order to remove the other elements at the end

See also Filter data in d3 to draw either circle or square

One other way to do it is to use the selection.each method: https://github.com/mbostock/d3/wiki/Selections#wiki-each
By using an if statement with the corresponding index you can create a block for one element.
E.g.

var data = [[0,0,2],[0,23,5],[2,12,5]];
var circleSet = svg.selectAll()
         .data(data)
         .enter()
         .append('circle')
         .each(function (d, i) {
            if (i === 1) {
              // put all your operations on the second element, e.g.
              d3.select(this).append('h1').text(i);    
            }
          });

Leave a Comment