In d3, when is it appropriate to use
d3.select("foo").attr('class', 'bar');
as opposed to
d3.select("foo").classed('bar', true);
?
Is one recommended or expected to be deprecated? What is industry standard?
D3 provides the ability to set attributes of a selected element using the attr() function. This function takes two parameters: Attribute Name - For example, "r" to set an SVG circle's radius.
d3. select selects the first matching element whilst d3. selectAll selects all matching elements. Both functions take a string as its only argument.
For example, d3. select returns a selection with one group containing the selected element: var selection = d3. select("body");
There is no appropriate method, or recommended, or standard. Both are valid methods, and deciding which one to use depends on your specific purpose.
The main difference between classed("foo", true)
and attr("class", "foo")
is that the former will only modify the classList if it already exists...
If a value is specified, assigns or unassigns the specified CSS class names on the selected elements by setting the class attribute or modifying the classList property and returns this selection. (emphasis mine)
... while the latter will override it.
Let's show the difference in a very simple demo.
There are already paragraphs with assigned classes in the DOM. We select them and use attr("class", "someClass")
in the selection. Then, we console.log
the class of each one:
var p = d3.selectAll("p"); p.attr("class", "someClass"); p.each(function() { console.log(d3.select(this).attr("class")) })
<script src="https://d3js.org/d3.v4.min.js"></script> <p class="foo">This paragraph has a class foo</p> <p class="bar">This paragraph has a class bar</p> <p class="baz">This paragraph has a class baz</p>
You can see that someClass
overrides the previously existing classes.
Now the same code using classed("someClass", true)
:
var p = d3.selectAll("p"); p.classed("someClass", true); p.each(function() { console.log(d3.select(this).attr("class")) })
<script src="https://d3js.org/d3.v4.min.js"></script> <p class="foo">This paragraph has a class foo</p> <p class="bar">This paragraph has a class bar</p> <p class="baz">This paragraph has a class baz</p>
As you can see, someClass
is added to the previously existing classes.
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