Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 add multiple classes with function

I have the svg as:

<g class="user" title="Michael" rel="tooltip" transform = "rotate(-12.364052661705784)translate(360)" style="fill: #9467bd; "></g> 

I want to add a class as the same as title. I tried

d3.selectAll('.user').attr('class','Michael'); 

But it replaced the original class. Then I tried

d3.selectAll('.user').classed('Michael',true); 

It works! But now I want to return the class name with a function like

d3.selectAll('.user').classed(function(){return this.attr('title');},true); 

It doesn't work. How can I do that?

Thanks

like image 680
Yujun Wu Avatar asked Nov 02 '12 01:11

Yujun Wu


1 Answers

You can assign multiple classes to elements by simply separating their names with spaces:

d3.selectAll(".user").attr("class", "user Michael"); 

But it seems that what you really need is to assign a data property to your elements for which it is much better to use the HTML5 data- attributes. So you could do:

d3.selectAll(".user").attr("data-name", function(d,i) { return "Michael #" + i; }); 

and later to obtain the name of a user:

d3.select(".user").attr("data-name") 
like image 149
Ilya Boyandin Avatar answered Oct 18 '22 04:10

Ilya Boyandin