-1

Very similar to other Jquery questions, but I cannot get around how to accomplish the same with pure d3 code

Ian
  • 33,605
  • 26
  • 118
  • 198
Loredra L
  • 1,485
  • 2
  • 16
  • 32

2 Answers2

1

You can do it like this:

d3.selectAll('li')
    .attr('color',function(d,i){
        console.log(this,i);
    })

I've made a fiddle which in console you can see the index.

http://jsfiddle.net/a2QpA/294/

eko
  • 39,722
  • 10
  • 72
  • 98
1

This comes down to understanding how D3 selections work. Whenever you're dealing with a selection and provide a function to be consumed you've got a standard set of parameters. All this is available in the documentation:

  • d is the datum parameter which represents the data bound to that element
  • i is the index parameter, this is the bit you're after!

this is also redefined, such it represents the DOM element that you are dealing with.

So an example would be:

d3.selectAll("li")
  .each(function(d, i) { 
      console.log("This <li> tag " + i);
  });
Ian
  • 33,605
  • 26
  • 118
  • 198
  • Thank you so much. The after I get the index, is it possible to use d3.select(ul).properties("ScrollTo",index) to move the scroller – Loredra L Apr 01 '16 at 15:46
  • @LoredraL that's a separate question really. However, as mentioned `this` is the actual element, so if you know which of those particular elements you want to scroll to, then you could pass `this` into a function like demonstrated in this answer http://stackoverflow.com/questions/4801655/how-to-go-to-a-specific-element-on-page . The important part being `$(this).offset().top + 'px'` – Ian Apr 01 '16 at 16:15