How can I use d3 classed selection to have name as function
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 d3.select(this).attr("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 = d3.select(this).attr("class")
if (existing == null){
return d.column.class
}else{
return existing + " " + d.column.class
}
})
This could be made into a one-liner with a ternary operator if you want it more concise
Similar to the suggested answer, but I found
selection.each(function(d) { d3.select(this).classed(d.class, true)
also works.
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 d.property; })
.classed('class-two', function(d) { return d.property; });
If you have a small number of classes to add then something like this might be worth considering.