Aidan Garnish

Collaboration Not Competition

Change class on an HTML element using javascript

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>

Add comment

Loading