Reputation: 1326
I am going to set various css styles on an svg element, and was thinking I could do something like
d3.selectAll(".whatever")
.style(function(d) { return {"color":getColor(d), "background":getBackground(d)}});
Now, this doesn't work, but I'm wondering if I can do something similar to centralize setting overall style properties rather than set style properties individually.
Note: as Ray suggested, you can do something like this (I'm assuming you've already got data attached to the nodes):
d3.selectAll(".whatever")
.attr("style",function(d) {
return cssStyleStringYouWantToUse(d);
});
Upvotes: 9
Views: 21333
Reputation: 523
The easiest way of applying multiple css (static or dynamic) in d3 is to set style
as many times as you need it. For example:
d3.selectAll('whatever')
.style('color', 'green')
.style('height', (d) => d + 'px');
Upvotes: 4
Reputation: 109282
Only works on D3 v3:
To quote the documentation:
If you want to set several style properties at once, use an object literal like so:
selection.style({'stroke': 'black', 'stroke-width': 2})
This isn't possible with functions though, so in your case you still have to use the "long form".
Upvotes: 11
Reputation: 3227
You can specify a separate function for each style name in the style literal, like so:
d3.selectAll(".whatever").style({
color: function(d) { return getColor(d); },
background: function(d) { return getBackground(d); }
});
Upvotes: 6