Throughout the post, we will be using the sample as follows:
<div id="example" class="firstClass secondClass"></div>
Add a class to selection
A class can be added by using classed with the new class as a string and boolean value true.
d3.select("#example").classed("addedClass", true);
The result:
<div id="example" class="firstClass secondClass addedClass"></div>
Remove a class
To remove a class, set the boolean parameter to false.
d3.select("#example").classed("firstClass", false);
The result obtained from the original example would be:
<div id="example" class="secondClass"></div>
Replace a set of classes
In case you don’t know about the existing classes or you simply want to remove all the classes and/or replace with a new value, you could use attr method.
d3.select(“#example”).attr(“class”, ”thirdClass”);
The result obtained from the original example would be:
<div id="example" class="thirdClass"></div>
Check the existence of a class
If the classed method is used without the second boolean parameter, it will return the existence of the defined class.
console.log(d3.select("#example").classed("firstClass"));
For the original example, the above code would print true.
Toggle a class
By using the above described pieces of code, we can write a method to toggle the class of a selection.
d3.select("#example").classed("newClass", !d3.select("#example").classed("newClass"));
The same could be written as:
var example = d3.select("#example"); example.classed("newClass", !example.classed("newClass"));
0 comments:
Post a Comment