Categories
JavaScript Answers

How to add multiple classes with function with d3 and JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *