Aidan Garnish
MOSS 2007 and other Microsoft technologies

Change class on an HTML element using javascript

September 3, 2008 09:45 by Aidan

A basic javascript function to toggle an elements class property.

<script language="javascript">
 function ToggleClass(id, class1, class2)
 {
  try
  {
   if(document.getElementById(id).className == class1)
   {
    document.getElementById(id).className = class2;
   }
   else
   {
    document.getElementById(id).className = class1;
   }
  }

  catch(e)
  {
     window.alert(e.description);
   }
 }

</script>

An example of how this can be used to hide and show sections in a page:

<html>
<style>
.Row
{
   float:left;
   clear:left;
}

.AddressRow
{
   float:left;
   clear:left;
   padding:0px 0px 5px 0px;
}

.AddressRowNoDisplay
{
   float:left;
   clear:left;
   padding:0px 0px 5px 0px;
   Display:None;
}

.Field
{
   float:left;
   padding-right:10px;
}

</style>

<head>

<script language="javascript">


 function ToggleClass(id, class1, class2)
 {
  try
  {
   if(document.getElementById(id).className == class1)
   {
    document.getElementById(id).className = class2;
   }
   else
   {
    document.getElementById(id).className = class1;
   }
  }

  catch(e)
  {
     window.alert(e.description);
   }
 }

</script></head>
<body>

<div class="Row">
<div class="Field">Aidan Garnish </div>
<div class="Field">0191 4562736</div>
<div class="Field"><a href="javascript:ToggleClass('Address1', 'AddressRow', 'AddressRowNoDisplay')">Show/Hide detail</a>
</div>
<div id="Address1" class="AddressRowNoDisplay">
55 Jumble Avenue, Googenheim, GH1 5SD
</div>

<div class="Row">
<div class="Field">Brian Cosby </div>
<div class="Field">0192 3568736</div>
<div class="Field"><a href="javascript:ToggleClass('Address2', 'AddressRow', 'AddressRowNoDisplay')">Show/Hide detail</a>
</div>
<div id="Address2" class="AddressRowNoDisplay">
37 Ungerton Road, Googenheim, GH1 7WS
</div>

<body>
</html>


Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:
Categories: CSS
Actions: E-mail | Permalink | Comments (2) | Comment RSSRSS comment feed

Related posts

Comments

September 3. 2008 10:11

What's wrong with a generic approach then? ;)

function getObject(objectID)
{
if ( document.getElementById )
return document.getElementById(objectID);

// put cross browser stuff in here....

return null;
}
function changeClass(ref, class1, class2)
{
var obj = getObject(ref);

if ( obj != null )
obj.className = (obj.className == class1) ? class2 : class1;
}

Tom

September 4. 2008 15:22

He he! Nice improvement Thomas. I have changed the code slightly so it takes 3 parameters and is more generic. I like the simplicity of my one function but as always there are many ways to get the skin off the cat. Smile

Aidan

Add comment


 

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

January 6. 2009 15:44