Dynamically modifying CSS class name attributes

CSS allows you to not only define the style attributes directly like
<span id="mySpan" style="font-weight:bold; color:blue;">
some text within the span container...
</span>
but to define separate classes which is what is actually done in order to separate the design from the layout:
Example of two CSS classes
  .blueText{    
color:blue;
}
.boldText{
font-weight:bold;
font-size:12pt;
}
In order to apply those styles you would then do something like the following
<span id="mySpan" class="blueText boldText">
some text within the span container...
</span>
As you see, you can assign both classes by separating them with a blank in between. But lets come to the point of this post. Assume now that you have to modify those class names dynamically depending on some user interaction (i.e. when the user changes the content of a text field or drop down list or whatever :) )
I've written some pieces of JavaScript for solving this problem. The script is written in a way that it is reusable.
Script
/*
* Adds the given CSS class dynamically to the passed DOM element
*/
function addClassName(element, classname){
if(element == null)
throw('Passed DOM element was null');

//see whether there is already a className present
if(element.className)
//append it
element.className += ' ' + classname;
else
element.className = classname;
}

/*
* Removes the given CSS class dynamically from the passed DOM element
*/
function removeClassName(element, classname){
if(element == null)
throw('Passed DOM element was null');

//see whether the classname to remove is really present
var regexMatch = element.className.match(' '+classname)?' '+classname:classname;
if(regexMatch != null){
element.className = element.className.replace(regexMatch,'');
}
}
Usage
function addBoldCSSClass(){
var span = document.getElementById('mySpan');
addClassName(span, 'b');
}

function removeBoldCSSClass(){
var span = document.getElementById('mySpan');
removeClassName(span, 'b');
}
Here's a very simple live demo.
Kindle

Comments

0

Your ad here?