2018-10-10 18:03:03 -04:00
---
id: 587d7fa7367417b2b2512bc8
2021-02-06 04:42:36 +00:00
title: Add Classes with D3
2018-10-10 18:03:03 -04:00
challengeType: 6
2020-09-18 00:13:05 +08:00
forumTopicId: 301473
2021-01-13 03:31:00 +01:00
dashedName: add-classes-with-d3
2018-10-10 18:03:03 -04:00
---
2020-12-16 00:37:30 -07:00
# --description--
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
Using a lot of inline styles on HTML elements gets hard to manage, even for smaller apps. It's easier to add a class to elements and style that class one time using CSS rules. D3 has the `attr()` method to add any HTML attribute to an element, including a class name.
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
The `attr()` method works the same way that `style()` does. It takes comma-separated values, and can use a callback function. Here's an example to add a class of "container" to a selection:
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
`selection.attr("class", "container");`
Note that the "class" parameter will remain the same whenever you need to add a class and only the "container" parameter will change.
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
# --instructions--
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
Add the `attr()` method to the code in the editor and put a class of `bar` on the `div` elements.
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
# --hints--
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
Your `div` elements should have a class of `bar` .
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
```js
assert($('div').attr('class') == 'bar');
2018-10-10 18:03:03 -04:00
```
2021-02-06 04:42:36 +00:00
Your code should use the `attr()` method.
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
```js
assert(code.match(/\.attr/g));
2018-10-10 18:03:03 -04:00
```
2020-08-13 17:24:35 +02:00
2021-01-13 03:31:00 +01:00
# --seed--
## --seed-contents--
```html
< style >
.bar {
width: 25px;
height: 100px;
display: inline-block;
background-color: blue;
}
< / style >
< body >
< script >
const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
d3.select("body").selectAll("div")
.data(dataset)
.enter()
.append("div")
// Add your code below this line
// Add your code above this line
< / script >
< / body >
```
2020-12-16 00:37:30 -07:00
# --solutions--
2021-01-13 03:31:00 +01:00
```html
< style >
.bar {
width: 25px;
height: 100px;
display: inline-block;
background-color: blue;
}
< / style >
< body >
< script >
const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
d3.select("body").selectAll("div")
.data(dataset)
.enter()
.append("div")
// Add your code below this line
.attr("class","bar");
// Add your code above this line
< / script >
< / body >
```