By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,946 Members | 773 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,946 IT Pros & Developers. It's quick & easy.

Dynamically Adding/Removing Classes

P: n/a
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/

Feb 3 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a
to*****@gmail.com wrote:
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>

--
Rob
Feb 3 '06 #2

P: n/a
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;
}
}

Feb 6 '06 #3

P: n/a
to*****@gmail.com wrote:
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;
}
}

--
Rob
Feb 6 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.