Thursday, 31 January 2008

Change HTML class attribute using javascript

If you are a JavaScript newbie this post helps you to implement a simple code to change the class for HTML elements.

Some readers asked to me how to change the class attribute of an HTML element using javascript. You can use setAttribute() in this way:


document.getElementById("idElement").setAttribute("class", "className");


...where className is the name of class you want to assign to your html element with ID equal to "idElement".

An example
Image you have a <div> element with a link which call a javascript function changeClass() to change the <div> class:

<div id="myElement">Welcome on my site!</div>
<a href="javascript:changeClass()"&gtChange Class</a>
<script language="javascript">
function changeClass(){
document.getElementById("idElement").setAttribute("class", "myClass");
}
</script>

No comments:

Post a Comment