I am using d3 classed selections and in first parameter, instead of a string, I want to use a function that will returns class name.
selection.classed(name[, value])
I understand I can do the same using .attr()
as mentioned here, but I want to be able to do the same using classed.
How can I do this?
select() function in D3. js is used to select the first element that matches the specified selector string. If any element is not matched then it returns the empty selection. If multiple elements are matched with the selector then only the first matching element will be selected.
d3. select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument.
attr() function is used to set the attribute of the element that is selected. The name of the attribute and value of the attributes are to be set using this 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; })
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With