Rajat Agarwal Rajat Agarwal - 25 days ago 13
Javascript Question

Adding multiple class name to an element D3

I am working on a D3 Scatter Plot having data from different regions - here regions are Continent names like Europe, Asia etc. I want to associate the region with a class name so that I can perform common activities for one region.

Below is my code to add multiple classes together to an element:

var dot = svg.append("g")
.attr("class", "dots")
.selectAll(".dot")
.data(interpolateData(1900))
.enter().append("circle")
.attr("class", "dot " + function(d) { return d.Region; });


When I write the following code to check what classes are associated with the current object.

alert(this.getAttribute('class'));


I got this output:

enter image description here

So I can see that it is adding "dot" class successfully but not able to add Region dynamically.

TIA

Answer

You have move your function, passing it as the second argument of attr:

.attr("class", function(d){
    return "dot " +  d.Region; 
});
Comments