Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
88
rated 0 times [  94] [ 6]  / answers: 1 / hits: 150511  / 15 Years ago, fri, may 29, 2009, 12:00:00

Suppose a HTML element's id is known, so the element can be refereced using:



document.getElementById(element_id);


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


More From » css

 Answers
21
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
$(element_id).addClassName(newClassName);


See how much nicer that is?!


[#99426] Tuesday, May 26, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradley

Total Points: 555
Total Questions: 102
Total Answers: 99

Location: Tajikistan
Member since Fri, Nov 27, 2020
4 Years ago
;