Accepted answer

The class name you provide there needs to be fixed, i.e. you cannot have something like function(d) { return d; }. If you need the class name to be determined by the data, you need to use .attr("class", ...).

If you're worried about overwriting existing class names, note that you can retrieve and prepend those as follows.

.attr("class", function(d) { return"class") + " " + d; })


Lars answer is great, but if you start out with no class on the attribute it will add the class 'null' to the element as the null attribute is forced to a string. Natural next step from his:

.attr("class", function(d) {
      var existing ="class") 
      if (existing == null){
        return d.column.class
        return existing + " " + d.column.class

This could be made into a one-liner with a ternary operator if you want it more concise


I encountered a similar problem in which I wanted to add one class if a property on my datum was true and a different class if the property was false:

selection.classed('class-one', function(d) { return; })
    .classed('class-two', function(d) { return; });

If you have a small number of classes to add then something like this might be worth considering.


Similar to the suggested answer, but I found

selection.each(function(d) {, true)

also works.

Related Query

More Query from same tag