D3.js How to apply multiple classes when using a function

Update

Seems, this approach no longer acceptable for D3.js v5+

Original answer

You can also use a hash as argument of classed function:

var circle = svg.selectAll("circle")
  .data(data)
  .enter()
  .append('circle')
  .classed({
    '2012': function(d) { return d['Year'] === 2012; },
    '2013': function(d) { return d['Year'] === 2013; },
    'set-1': function(d) { return d['Set'] === 1; },
    'set-2': function(d) { return d['Set'] === 2; }
  });

There is an alternative approach that can be useful. You can assign or remove classes from an element using selection.classed('class-name', true) or selection.classed('class-name', false):

var circle = svg.selectAll("circle")
    .data(data)
    .enter()
    .append('circle')
    .classed('2012', function(d) { return d['Year'] === 2012; })
    .classed('2013', function(d) { return d['Year'] === 2013; })
    .classed('set-1', function(d) { return d['Set'] === 1; })
    .classed('set-2', function(d) { return d['Set'] === 2; });

I prefer this way because you can remove the classes from an element using the same syntax.


You just want a single function that does both things don't you. Something along these lines perhaps...

var circle = svg.selectAll("circle")
        .data(data)
        .enter()
        .append("circle")
        .attr("class", function(d) {
            var c = "";
            if (d["Set"] == 1)
            {
                c = "set-1";
            }
            if (d["Set"] == 2)
            {
                c = "set-2";
            }
            if (d["Year"] == 2012)
            {
                c += " 2012";
            }
            if (d["Year"] == 2013)
            {
                c += " 2013;
            }
            return c;
        });