Reputation: 11
I am trying to change CSS properties of all div elements where class=item (by accessing the div elements using D3 selectAll()). I am able to change only single property using style() but when I try to pass object to style() nothing happens. For example this works fine:
var myData = [{width: 100, background: '#FF0000'}, {width: 140, background: '#B22222'}]
d3.selectAll('.item').data(myData).style('background',function(d){ return d.background})
But, this doesn't:
d3.selectAll('.item').style({'background': function(d){ return d.background }, 'width': function(d){return d.width } })
I read somewhere that styles() must be used instead of style() when passing an object but even styles() does not work. Here is the codepen link containing the code : http://codepen.io/anon/pen/JEoXOV
Can someone tell me what I am missing out here ?
Upvotes: 0
Views: 1011
Reputation: 5549
According to d3.js documentation https://github.com/d3/d3-selection#selection_style selection.style(name,value)
accepts single name-value pairs (value can be a constant or a function accepting d,i,data as usual), but not objects
If you want to set multiple style properties, you need to use multiple style() functions
d3.selectAll('.item')
.style('background', function(d){ return d.background; })
.style('width', function(d){return d.width; });
EDIT: Or use the d3-selection-multi library as Eric Guan pointed in his answer: https://stackoverflow.com/a/41474957/79536
Upvotes: 1
Reputation: 15982
Mike Bostock moved stuff around in v4.
https://github.com/d3/d3-selection/blob/master/README.md#selection_style
For the sake of parsimony, the multi-value methods—where you pass an object to set multiple attributes, styles or properties simultaneously—have been extracted to d3-selection-multi and are no longer part of the default bundle. The multi-value map methods have also been renamed to plural form to reduce overload: selection.attrs, selection.styles and selection.properties.
Upvotes: 2