Issue
D3 has 2 ways of setting a class:
selection.attr("class", (d) => d.isFoo ? "foo" : "");
selection.classed("foo", (d) => d.isFoo)
I'm looking for a way to add a class named as per the data. I.e. something like:
selection.classed((d) => "node" + d.id, true);
- I don't want to use
id
because multiple DOM elements will share that class. - I don't want to use
attr
because it may potentially overwrite other classes already there.
So I could do
selection.attr("class", (d) => d3.select(this).attr("class") + " node" + d.id);
which feels a bit hackish.
Any better solution? Or a feature underway?
Solution
Although Gerardo's answer is correct and comes with a proper explanation, I think, the easiest way to mess with an element's classes is to resort to its classList
property which it inherits from the Element
interface.
The
Element.classList
is a read-only property which returns a liveDOMTokenList
collection of the class attributes of the element.
Although the property itself is read-only, it provides methods for adding, removing and toggling classes. Calling .add()
will automatically take care of classes previously set and check if the class to add has already been assigned to the element:
add( String [, String] )
Add specified class values. If these classes already exist in attribute of the element, then they are ignored.
Adding a class based on data can thus be done using selection.each()
:
divs.each(function(d) {
this.classList.add("node" + d.name);
});
Within the .each()
method this
points to the actual element and can be used to directly access the classList
property.
var data = [{name: "foo"},
{name: "bar"},
{name: "baz"}];
var body = d3.select("body");
var divs = body.selectAll("myDivs")
.data(data)
.enter()
.append("div")
.attr("class", "someClass");
divs.each(function(d) {
this.classList.add("node" + d.name);
});
//log the classes, you can see the previous class ("someClass") was not overwritten:
divs.each(function() {
console.log(d3.select(this).attr("class"))
})
<script src="https://d3js.org/d3.v4.min.js"></script>
Answered By - altocumulus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.