views:

471

answers:

8

Hi,

I have a element that already has a class:

<div class="someclass">
          <img ... id="image1" name="image1" />
</div>

Now I want to create a javascript function that will add a class to the div (not replace, but add).

How can I do that?

+12  A: 

Use the className property of the element. First, put an id on the div so you can easily get a reference.

<div id="div1" class="someclass">
    <img ... id="image1" name="image1" />
</div>

Then

var d = document.getElementById("div1");
d.className = d.className + " otherclass";
Ishmael
+1 for answer in JavaScript, as the question requested. Dragging in many thousands of lines of framework for a one-liner is not sensible.
bobince
+1 for not pushing a framework down the OP's throat.
Paolo Bergantino
If the only work on the whole page that needs to be done with JavaScript is this class name addition, then yes. But I can't see this being the only dynamic part of the page. A library will help with everything else as well. At 30-50kb jQuery is hardly a hit worth discussing.
thenduks
"A library will help with everything else as well" - apart from learning JavaScript
meouw
What does adding a class to a DOM element have to do with learning the language? document.getElementById('div1').className is as much a library related issue as using jQuery to do the same is. The question was "how can I do that", a thoroughly tested library is the sensible answer.
thenduks
@thenduks: I'm sure you know that JavaScript !== jQuery. It's a good thing that the answers to this question include library and non library solutions because it is important to know *how* things work not just the simplest way to accomplish them. You'll notice this question is tagged javascript
meouw
@meouw: I agree with you. jQuery is written _in_ JavaScript, however, so I maintain that mentioning to the OP that a library is a good idea is not 'pushing a framework down [his] throat'. That's all.
thenduks
A: 

By using the prototype library I think it's something like this :

$$(".someclass").each(function(element) {
    element.addClassName("otherclass");
});
Vinze
This is jQuery specific though.
Rocco
No, this is Prototype specific :p that's why I said "using prototype library"
Vinze
+1  A: 

Assuming you're doing more than just adding this one class (eg, you've got asynchronous requests and so on going on as well), I'd recommend a library like Prototype or jQuery.

This will make just about everything you'll need to do (including this) very simple.

So let's say you've got jQuery on your page now, you could use code like this to add a class name to an element (on load, in this case):

$(document).ready( function() {
  $('#div1').addClass( 'some_other_class' );
} );

Check out the jQuery API browser for other stuff.

thenduks
+1 because jQuery is great!
meouw
+2  A: 

find your target element "d" however you wish and then:

d.className += ' additionalClass'; //note the space

you can wrap that in cleverer ways to check pre-existance, and check for space requirements etc..

annakata
A: 

first, give the div an id. Then, call function appendClass:

<script language="javascript">
  function appendClass(elementId, classToAppend){
    var oldClass = document.getElementById(elementId).getAttribute("class");
    if (oldClass.indexOf(classToAdd) == -1)
    {
      document.getElementById(elementId).setAttribute("class", classToAppend);
    }
}
</script>
tehvan
it will replace the class not append ! Maybe be a line is missing or a oldClass+" "+classToAppend instead of the last classToAppend
Vinze
+1  A: 

In YUI, if you include yuidom, you can use

YAHOO.util.Dom.addClass('div1','className');

HTH

Alagu
+2  A: 

Just to elaborate on what others have said, multiple CSS classes are combined in a single string, delimited by spaces. Thus, if you wanted to hard-code it, it would simply look like this:

<div class="someClass otherClass yetAnotherClass">
      <img ... id="image1" name="image1" />
</div>

From there you can easily derive the javascript necessary to add a new class... just append a space followed by the new class to the element's className property. Knowing this, you can also write a function to remove a class later should the need arise.

CodeMonkey1
A: 

When the work I'm doing doesn't warrant using a library, I use these two functions:

function addClass( classname, element ) {
    var cn = element.className;
    //test for existance
    if( cn.indexOf( classname ) != -1 ) {
     return;
    }
    //add a space if the element already has class
    if( cn != '' ) {
     classname = ' '+classname;
    }
    element.className = cn+classname;
}

function removeClass( classname, element ) {
    var cn = element.className;
    var rxp = new RegExp( "\\s?\\b"+classname+"\\b", "g" );
    cn = cn.replace( rxp, '' );
    element.className = cn;
}
meouw