How can I change a CSS class of an HTML element in response to an onClick
event using JavaScript?
views:
64773answers:
6This is easiest with a library like jQuery:
<input type="button" onClick="javascript:test_byid();" value="id='second'" />
<script>
function test_byid()
{
$("#second").toggleClass("highlight");
}
</script>
No offense, but it's unclever to change class on-the-fly as it forces the css-interpretator to recalculate the visual presentation of the entire webpage ...
-- the reason is that it is nearly impossible for the css-interpretator to know if any inheritance or cascading could be changed, so the short answer is:
Never ever change className on-the-fly !-)
But usually you'll only need to change a property or two, and that is easily implemented:
function highlight(elm){
elm.style.backgroundColor ="#345";
elm.style.color = "#fff";
}
You can use node.className like so:
document.getElementById("blah").className = "cssclass";
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(/\bMyClass\b/','')
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 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>
this line: document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/\bMyClass\b/','')
should be: document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace('/\bMyClass\b/','');
@Eric Bailey You are right, there is an error there but your correction is not good. If you put the regex into quote, it will try to find the string instead of executing the regex. The right correction is:
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/\bMyClass\b/','')
should be:
document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/\bMyClass\b/,'');