Dynamically Adding/Removing Classes

T

tomlong

In my last job we had a crummy function that did regex to add/remove
css classes to an element.

Does anyone have a better way to do this? Techniques or code would be
great. I'm almost surprised this isn't in prototype.js after finding
Element.cleanWhiteSpace(el) today.

Thanks!
Tom Longson (nym)
http://igargoyle.com/
 
R

RobG

In my last job we had a crummy function that did regex to add/remove
css classes to an element.

Does anyone have a better way to do this? Techniques or code would be
great. I'm almost surprised this isn't in prototype.js after finding
Element.cleanWhiteSpace(el) today.


<style type="text/css">
.red {color: red;}
.bb {font-weight: bold;}
.uu {text-decoration: underline;}
</style>


<script type='text/javascript'>

function deleteCSSClass(el, cssClass)
{
var c = el.className;
var re = new RegExp('\\b' + cssClass + '\\b','g');
if (c) el.className = cleanClassWhitespace( c.replace(re, '') );
}

function addCSSClass(el, cssClass)
{
el.className += ' ' + cssClass;
}

function cleanClassWhitespace(s)
{
return s.replace(/^\s+/,'').replace(/\s+/g,' ').replace(/$\s+/,'');
}

</script>


<span onclick="deleteCSSClass(this, 'red');" class="bb red uu">
click to remove .red class
</span>
 
T

tomlong

That's great. Here's one addition that makes it a tiny bit better (but
not by much). All I did was add a check to see if the className was
already there so if you add a class more than once, you don't have to
remove it multiple times.

function addCSSClass(el, cssClass)
{
if(el.className.indexOf(cssClass) == -1) {
el.className += ' ' + cssClass;
}
}
 
R

RobG

That's great. Here's one addition that makes it a tiny bit better (but
not by much). All I did was add a check to see if the className was
already there so if you add a class more than once, you don't have to
remove it multiple times.

function addCSSClass(el, cssClass)
{
if(el.className.indexOf(cssClass) == -1) {
el.className += ' ' + cssClass;
}
}

Yes, good idea. You should use a regular expression to ensure you match
whole words, indexOf will match 'blah' in 'blah' and 'blah2':

function addCSSClass(el, cssClass)
{
var re = new RegExp('\\b' + cssClass + '\\b');
if(!re.test(el.className)) {
el.className += ' ' + cssClass;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top