how to change css class name using javascript

Most of the programmers don’t know about how to change css class name using javascript, specially beginners.Its very easy to change css style using javascript on any event .You just have to make a javascript function with one line and call that function on any event like onLoad , onclick etc.

suppose you want to chane css of a div when click on a button or any link.A simple div which has some text and on click on a button you want to change the border color and background color of that div.To do this first make your css class in your .css file .

example:
.cssclass{ border:1px solid #000;background-color:#000}

Now make a javascript function to apply css class at run time.But remember one thing for proper working of this script you must have given a id to that div like:
<div id=”test”></div>

<script type=”text/javascript”>
function changeClass()
{
document.getElementById(”test”).className = “cssclass”;

}
</script>

After this just call this javascript function on onclick event of that button:
<input type=”button” name=”test” onclick=”changeClass();” />

That’s it.Now when you will click on button at run time the class “cssclass” will apply on that div without a moment.

Remember on thing that this class will apply only from that moment to when you will reload the page means if you will reload the page then script will show the old class again rather then new class.

This is just one example , you can change all the styles of an element using javascript.

Related posts:

  1. JavaScript Arrays
  2. How to speed up my site

2 Responses to “how to change css class name using javascript”

  1. Julian Decraene Says:

    I just needed to say that I found your site via Goolge and I am glad I did. Carry on the great work and I will be sure to bookmark you for when I have a lot more totally free time away from the books. Thanks!


  2. Ocie Raith Says:

    I just needed to say that I found your website via Goolge and I am glad I did. Continue the very good work and I will ensure to bookmark you for when I have additional free of charge time away from the books. Thanks!


Leave a Reply

XHTML: You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>