Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Treehouse Club - MASH MASH - HTML Forms, Divs, and Inputs

How do I add a class attribute to a div?

I am trying to add class to the div element. I was putting <div class="favorite_stuff"> What am I doing wrong?

index.html
<body>
  <h1>First Day of School</h1>

  <form>

    <div>
      <h4>Favorite Foods?</h4>
      <input name="food[]"><div class="favorite_food">
      <input name="food[]">
      <input name="food[]">
      <input name="food[]">
    </div>

    <div>
      <h4>Favorite Animals?</h4>
      <input name="animal[]">
      <input name="animal[]">
      <input name="animal[]">
      <input name="animal[]">
    </div>

  </form>

</body>

2 Answers

Kevin Korte
Kevin Korte
28,149 Points

It's just simply

<div class="my-class"></div>
Maxwell DeMers
Maxwell DeMers
6,853 Points

Because you posted this under "Javascript", I thought I'd add a javascript way of doing this. First, you will need to add an id to the you want to change

<div id="my-div"></div>

Then, you can select the div using javascript, and change/add the class like so

document.getElementById("my-div").className = "my-class";

Because there isn't a class to begin with, you can just set the class name like I've done above. However, there are other ways to manipulate the class names if there are already ones there.

Happy coding!