Michael Conn Michael Conn - 1 year ago 168
CSS Question

d3.selectAll to change styles by class in v4

I'm transitioning from d3 v3 to d3 v4. I've looked through the documentation on what's changed, and I know that styles and selectors work a little differently now. I'm having an issue finding the right way to get what I need done.

In v3 I could do this:

d3.selectAll(".myRectangle").style({'fill':'rgb(255,100,100)', 'stroke':'#000', 'stroke-width':'0.3'});

at the bottom of my code and everything that was classed as "myRectangle" that had been drawn would get the specified style applied to it.

Also, it would act as a placeholder in case anything dynamically got the myRectangle class added to them (say with a mouseover).

Now, the same code not only doesn't apply the styles, it returns an error if no element with the specified class exists.

I haven't been able to find an example of how to properly achieve this, which, might mean that I've been doing it poorly all along. Can anyone here point me in the right direction?

Answer Source

In d3.js v4, attr and style only accept one attribute/value pair as parameters:

d3.selectAll('.myRectangle').style('fill', 'rgb(255,100,100)')

In order to pass an object with multiple values, you have to use attrs and styles instead of attr and style and also include https://d3js.org/d3-selection-multi.v0.4.min.js file in your web page.

Alternatively, you may chain several attr, one for each attribute. Idem for style.

Reference: d3-selection-multi

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download