how to change css class name using javascript
Nov 3, 2009 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.
Tags: background, border, change style, classname, css, css class, getElementById, Javascript, javascript function, onclick, reload, runtime, stylesheet
December 3rd, 2009 at 7:43 am
Dude, u just did a great job.This post is really helpful.Thanks for sharing, I will feed your posts.
December 29th, 2009 at 5:05 am
I have more than 12 nich markets im interested in. Most interesting ins the advertising markets in the midwest. I did business in overland park kansas with a few local ad agencies and let me tell ya this is a cut throat industry. My strong points are in search engine optimization, pay per click adwords, omniture and social media setup. seo overland park kansas