2018-09-30 23:01:58 +01:00
---
id: 587d7fa7367417b2b2512bc8
title: Add Classes with D3
required:
- src: 'https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js'
challengeType: 6
---
## Description
< section id = 'description' >
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 < code > attr()< / code > method to add any HTML attribute to an element, including a class name.
The < code > attr()< / code > method works the same way that < code > style()< / code > 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:
< code > selection.attr("class", "container");< / code >
< / section >
## Instructions
< section id = 'instructions' >
Add the < code > attr()< / code > method to the code in the editor and put a class of < code > bar< / code > on the < code > div< / code > elements.
< / section >
## Tests
< section id = 'tests' >
```yml
2018-10-04 14:37:37 +01:00
tests:
- text: Your < code > div</ code > elements should have a class of < code > bar</ code > .
2018-10-08 01:01:53 +01:00
testString: 'assert($("div").attr("class") == "bar", "Your < code > div< / code > elements should have a class of < code > bar< / code > .");'
2018-10-04 14:37:37 +01:00
- text: Your code should use the < code > attr()</ code > method.
2018-10-08 01:01:53 +01:00
testString: 'assert(code.match(/\.attr/g), "Your code should use the < code > attr()</ code > method.");'
2018-09-30 23:01:58 +01:00
```
< / section >
## Challenge Seed
< section id = 'challengeSeed' >
< div id = 'html-seed' >
```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];
2018-10-08 01:01:53 +01:00
2018-09-30 23:01:58 +01:00
d3.select("body").selectAll("div")
.data(dataset)
.enter()
.append("div")
// Add your code below this line
2018-10-08 01:01:53 +01:00
2018-09-30 23:01:58 +01:00
// Add your code above this line
< / script >
< / body >
```
< / div >
< / section >
## Solution
< section id = 'solution' >
```js
// solution required
```
< / section >