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
  • 47,849
  • 12
  • 88
  • 91
  • `` added in header - dont work then tried near of this div tag, nothing too – elwins Jul 10 '12 at 13:24
  • 1
    @elwins - Seems to work: http://jsfiddle.net/f3YCG/ – Rob Hruska Jul 10 '12 at 13:31
  • 1
    @RobHruska I have added related note about elwins comment – Engineer Jul 10 '12 at 13:32
  • hmm, then how to correctly add it to web? – elwins Jul 10 '12 at 13:40
  • @elwins Try like this: `window.onload=function(){ var elem = document.getElementById("text-6"); elem.setAttribute("class", elem.getAttribute("class")+" fit"); };`. – Engineer Jul 10 '12 at 13:43
2

You put the following between your script tags.

document.getElementById('text-6').className += " fit";
Marcus Recck
  • 5,075
  • 2
  • 16
  • 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,374
  • 1
  • 24
  • 37
  • 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