D3 | .attr / CSS / .style

Sundar Singh
3 min readOct 12, 2017

When to use which when using d3js?

Let’s say we have this html :

<svg width="200" height="200">
<circle cx="100" cy="100" r="50"></circle>
</svg

Which is an SVG containing a circle, that will default to a black fill:

1. Using selection.attr()

If we use selection.attr we can make the circle red:

d3.select('circle').attr('fill', 'red')

this will change the circle part of the DOM to the folowing:

<circle cx="100" cy="100" r="50" fill="red"></circle>

2. Using CSS

Using CSS we can target the circle and achieve the same.

circle {
fill: green;
}

This will change the circle to green (but won’t change the DOM).

The circle will be green, even if we used the the rendered DOM from the first example using attribute to apply the fill:

<circle cx="100" cy="100" r="50" fill="red"></circle>

The css takes precedence over the attr

3. Using selection.style()

If we use selection.style will make a circle blue:

d3.select('circle').style('fill', 'blue')

The style takes precedence over the both the css and attr. It basically becomes inline CSS, with the circle part of the DOM being :

<circle cx="100" cy="100" r="50" style="blue"></circle>

Note: the circle will be blue, even if we used both the rendered DOM from the first example and had applied the css from the second example.

So when to use which?

I’d say use css whenever you can, then attr. Use style bearing in mind it’s inline and can be a pain to edit outside the code. It can be handy when you are basing the style on an interaction that needs to ensure precedence, or something like this, when that circle inherits settings passed in via an API:

const config = {
colour: 'yellow'
}
selection.on('mouseover', function() {
d3.select('circle')
.style('fill', 'config.colour')
}

So we know that our circle will be yellow, even if it has other base settings/defaults:

Hope this article is useful, let me know if it can be improved or anything else. I’m going to try and cover a series of articles on some of the ‘simple’ but easily overlooked things when working with d3js.

--

--

Sundar Singh

Exploring the intersection of beautiful design complexities and everyday life.