omg omg - 1 year ago 83
CSS Question

how to append a css class to an element by javascript?

Suppose a HTML element's

is known, so the element can be refereced using:


Does a native Javascript function exist that can be used to append a CSS class to that element?

Answer Source
var element = document.getElementById(element_id);
element.className += " " + newClassName;

VoilĂ . This will work on pretty much every browser ever. The leading space is important, because the className property treats the css classes like a single string, which ought to match the class attribute on HTML elements (where multiple classes must be separated by spaces).

Incidentally, you're going to be better off using a Javascript library like prototype or jQuery, which have methods to do this, as well as functions that can first check if an element already has a class assigned.

In prototype, for instance:

// Prototype automatically checks that the element doesn't already have the class

See how much nicer that is?!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download