Sergei Basharov
Sergei Basharov

Reputation: 53850

How to get an item from d3 collection by index?

I have an array ["a", "b", "c", "d"] from which I build two svg objects on the page. In first there is a chart and in second svg there are controls for this chart. Both have elements bound to the same data from the array. I want to use controls area as buttons to make chart elements active according to a clicked button from controls area.

If I click a button, I receive index in its click event and want to make a chart element active by highlighting it with a color. First I make chart elements then buttons area, both in the same way, like this:

    elements = d3.select('g.elements')

So, I have elements object for the chart, and an index from the click event, which I hope I can use to get respective item from this object in d3 way.

Please advise how I can get an object from elements with a specific index properly so that I can handle it with d3 methods and properties, not just as a DOM element?

Upvotes: 0

Views: 728

Answers (1)

Glenn
Glenn

Reputation: 5342

Not entirely clear. Do you want to do this:

d3.select("elements").each(function(d,i) {
    if(i == myIndex) {
        //do stuff
    }
})

This can be done using filter / select as well.

My view is that the d3.js way is to annotate the original data and draw the entire view again. So if your data was [{id:"a"}, {id:"b"},...] then when "a" was pressed you might update the object to: {id:"a", pressed:true}, and then redraw your two svg objects based on the new data (making "a" active based on the presence of "pressed" being true.

Upvotes: 1

Related Questions