Dynamically modifying CSS class name attributes
2 min read
2 min read
<span id="mySpan" style="font-weight:bold; color:blue;">but to define separate classes which is what is actually done in order to separate the design from the layout:
some text within the span container...
</span>
.blueText{In order to apply those styles you would then do something like the following
color:blue;
}
.boldText{
font-weight:bold;
font-size:12pt;
}
<span id="mySpan" class="blueText boldText">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 :) )
some text within the span container...
</span>
/*Usage
* 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,'');
}
}
function addBoldCSSClass(){Here's a very simple live demo.
var span = document.getElementById('mySpan');
addClassName(span, 'b');
}
function removeBoldCSSClass(){
var span = document.getElementById('mySpan');
removeClassName(span, 'b');
}