Can you set style in d3 via something like{color:blah, background:blah})?

Solution 1

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:{'stroke': 'black', 'stroke-width': 2})

This isn't possible with functions though, so in your case you still have to use the "long form".

Solution 2

You can specify a separate function for each style name in the style literal, like so:

    color: function(d) { return getColor(d); },
    background: function(d) { return getBackground(d); }

Solution 3

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');

Author by


Updated on June 13, 2022


  • Admin
    Admin about 2 months