Share this blog!

Handling classes with d3

Here is a list of some helpful uses of d3’s class operations using the methods classed and attr.

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"));




Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment