score:87

Accepted answer

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

score:0

Ilya's answer is good, but if you want to stay inside of the d3.select().classed() box the best way to add a class from data is to use the attr to add a class:

.attr('class', function (d) { return d.class })

However that will replace the class with that class, so if you want to add multiple classes then you have to do it in one line.

.attr('class', function (d) { return d.class + " " + d.otherclass})

This is limited as you can't really append classes, but I believe it also solves OPs question.

score:6

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.

score:10

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

Related Query

More Query from same tag