elegantly accessing the nth element of a selection

2,373 views
Skip to first unread message

jerome cukier

unread,
Nov 16, 2011, 11:00:18 AM11/16/11
to d3-js
Is there a simple way of doing that?


for instance I can do ...selectAll(" ... ").filter(function(d,i)
{return i==n;})
but is there a cleaner way of doing it?

Chris Viau

unread,
Nov 16, 2011, 11:07:13 AM11/16/11
to d3...@googlegroups.com
I use the nth-child pseudo class CSS selector, something like this:
d3.select("...:nth-child(n)")

Kyle Foreman

unread,
Nov 16, 2011, 11:41:02 AM11/16/11
to d3...@googlegroups.com
So I do this all the time for accessing the n-th option within a form select:

d3.select('#dropdown')[0][0][n]

But it doesn't work for selecting elements within an svg. Not sure if that's due to differences in how svg dom is structured or what.

jerome cukier

unread,
Nov 16, 2011, 11:47:39 AM11/16/11
to d3-js
ok Chris you win an extra question.
is there a way to set up styles of a pseudo-class? for instance hover.
AFAIK doing d3.selectAll("element:hover").style(...) doesn't work.
not that I need to do this currently but I once tried this and
couldn't do it without writing out the css outside of the code.


On 16 nov, 17:07, Chris Viau <christophev...@gmail.com> wrote:
> I use the nth-child<http://reference.sitepoint.com/css/pseudoclass-nthchild> pseudo

Chris Viau

unread,
Nov 16, 2011, 11:57:46 AM11/16/11
to d3...@googlegroups.com
Works for me on SVG:

element.selectAll(".bar:hover")
    .style("fill", "red");
or
element.selectAll(".bar:hover")
    .each(function(){return d3.select(this).style("fill", "red");});

Can you post a non-working example on jsfiddle?

Chris Viau

unread,
Nov 16, 2011, 12:01:09 PM11/16/11
to d3...@googlegroups.com
But you are right, it's only working on the special case where you select something with D3 with your cursor already on the element...
Reply all
Reply to author
Forward
0 new messages