.attr vs .classed in D3.js

In d3, when it is appropriate to use

d3.select("foo").attr('class', 'bar');

      

Unlike

d3.select("foo").classed('bar', true);

      

?

Can it be recommended or expected to be deprecated? What is an industry standard?

+3


source to share


2 answers


I think this classed

is some kind of conditional check, for example: To add a class, the second parameter for the class must be true, as in this code:

  d3.selectAll(".bar")
 .classed("my-selector", true);

      

To remove a class, the second parameter for the class must be false.

   d3.selectAll(".bar")
  .classed("my-selector", false);

      



To flip a class to its opposite state - remove it if it already exists, add it if it doesn't already exist - you can do one of the following.

For one element, the code might look like this:

var oneBar = d3.select(".bar")
oneBar.classed("my-selector", !oneBar.classed("my-selector"));

      

Both class and attr are of the same importance, but attr

are different uses that classed

cannot be used for.  To repeat

+2


source


There is no suitable method, or recommended, or standard. Both are valid methods, and the decision on 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 theList class if it already exists ...

If set, assigns or unassigns CSS class names to the selected elements by setting a class attribute or modifying the classList property and returns that selection. (emphasis mine)

... while the latter will override it.

Show the difference in a very simple demo.

There are already paragraphs in the DOM with assigned classes. We choose them and use them attr("class", "someClass")

in the selection. Then we console.log

class 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>
      

Run codeHide result


You can see what someClass

overrides the pre-existing classes.

Now the same code with 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>
      

Run codeHide result


As you can see, someClass

added to the pre-existing classes.

+9


source







All Articles