1

Possible Duplicate:
Change an element's CSS class with JavaScript

Found lot of topics about this topic, but none helped me. I have:

<div id="text-6" class="block col-228">

Javascript code should add new class fit, so result should be:

<div id="text-6" class="block col-228 fit">

How to do that with javascript?

Community
  • 1
  • 1
elwins
  • 49
  • 3
  • 2
    For future searching, [here's how I found that](https://www.google.com/search?q=javascript+add+class+to+element). – Rob Hruska Jul 10 '12 at 13:18

3 Answers3

3

Try like this:

var elem = document.getElementById("text-6");
elem.setAttribute("class", elem.getAttribute("class")+" fit");

Important note: You need to be assure,that your DOM Hierarchy is constructed completely,then try to manipulate DOM Elements. That is why you need to put DOM manipulation scripts inside of the window.onload callback, or if you use jQuery, then inside of $(document).ready callback.

Engineer
  • 45,891
  • 11
  • 86
  • 90
2

You put the following between your script tags.

document.getElementById('text-6').className += " fit";
Marcus Recck
  • 5,015
  • 2
  • 15
  • 26
2

I'd recommend using jQuery. Then you can just do something like this:

$("#text-6").addClass("fit");

EDIT:

Including the whole jQuery library may be overkill for your situation, but if you're dealing with DOM manipulation a lot, jQuery can simplify things quite a bit. If it's just for this one thing, then some of the other answers provided would be better.

Spectre87
  • 2,304
  • 1
  • 22
  • 36
  • 2
    Can't say I advocate including the entire source of jQuery just to add one classname to one element. Seems a little overkill... – danwellman Jul 10 '12 at 13:18
  • @danwellman I've edited my answer - I was assuming that multiple manipulations were going to be done, and that the question was just about how to get it done. – Spectre87 Jul 10 '12 at 13:26