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:".user").attr("data-name")


Ilya's answer is good, but if you want to stay inside of the 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.


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


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.

        var elt =;
        elt.classed(elt.attr("title"), true);

Related Query

More Query from same tag