d3 add multiple classes with function

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

If you just want to add a class, you can jump out of d3 and use the class list:

d3.selectAll('.user').node().classList.add("mynewclass");

Might not work in very old browsers tho.


why use HTML5 data attributes, duplicating data that is already there in the title attribute? HTML5 data attributes sure are useful, but duplicating data is not a good thing.

There is an easy of doing it without data duplication, being close to what you had in mind originally.

d3.selectAll('.user').each(
    function(){
        var elt = d3.select(this);
        elt.classed(elt.attr("title"), true);
    }
)