There are some great uses for changing an objects class via script. One of them is form elements. To create a better user experience, and guide them through the form, we can change the elements based on classes to show, hide and highlight the path way for the user.
To add a class to an element:
document.getElementById("MyElement").className += " MyClass";
To remove a class from an element:
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace ( /(?:^|s)MyClass(?!S)/g , '' ) /* code wrapped for readability - above is all one statement */
To do that in an onclick event:
<script type="text/javascript"> function changeClass() { // code examples from above } </script> ... <button onclick="changeClass()">My Button</button>
Better yet, use a framework (in this example jQuery) which allows you to do the following:
$j('#MyElement').addClass('MyClass'); $j('#MyElement').removeClass('MyClass'); $j('#MyElement').toggleClass('MyClass');
And also:
<script type="text/javascript"> function changeClass() { // code examples from above } $j(':button:contains(My Button)').click(changeClass); </script> ... <button>My Button</button>