suppose id is known,
so the element can be specified by document.getElementById(element_id);
but I don't know if there is a built-in function that can be used to append a css class to
that element?
suppose id is known,
so the element can be specified by document.getElementById(element_id);
but I don't know if there is a built-in function that can be used to append a css class to
that element?
var element = document.getElementById(element_id);
element.className += " " + newClassName;
voila. 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
$(element_id).addClassName(newClassName);
See how much nicer that is?!
You should be able to set the className property of the element. You could do a += to append it.
When an element already has a class name defined, its influence on the element is tied to its position in the string of class names. Later classes override earlier ones, if there is a conflict.
Adding a class to an element ought to move the class name to the sharp end of the list, if it exists already.
document.addClass= function(el, css){
var tem, C= el.className.split(/\s+/), A=[];
while(C.length){
tem= C.shift();
if(tem && tem!= css) A[A.length]= tem;
}
A[A.length]= css;
return el.className= A.join(' ');
}