To add multiple classes with function with d3 and JavaScript, we use the attr
method.
For instance, we write
d3.selectAll(".user").attr("data-name", (d, i) => {
return `Michael #${i}`;
});
to select all elements with class user
with selectAll
.
And then we call attr
with the attribute name we want to set for each selected element.
The callback returns the value of the data-name
attribute. And i
is the index of the element being iterated through to set the attribute.