[thelist] DOM: Getting elements with class="foo"? Solution & TIP!

Christian Heilmann codepo8 at gmail.com
Fri Nov 25 10:17:06 CST 2005


Can we please check things via the list before they become a tip?

<tip type="Javascript/DOM: Toggle table row visibility redux"
author="Christian Heilmann">

Re: earlier tip by Frank Marion

1) It is not a clever idea to hide things via CSS and show them via
JavaScript. If JavaScript is not available, then visitors will _never_
be able to see the content.

2) You can avoid the whole document.all malarkey by simply changing
from display block to no definition at all, the browser will choose
what is best for it.

3) testing for word boundaries in the class Check is not enough (Dean
Edwards had some cases on his page but I cannot find it now). The
right regExp is:
new RegExp("(^|\s)" + c1 + "(\s|$)").test(o.className)

4) Using addEvent is more flexible than onclick handlers, however, for
this example fair enough.

I am using the following function/method to remove, check, swap or add classes:
function cssjs (a,o,c1,c2){
		switch (a){
			case 'swap':
				o.className=!cssjs('check',o,c1)?o.className.replace(c2,c1):o.className.replace(c1,c2);
			break;
			case 'add':
				if(!cssjs('check',o,c1)){o.className+=o.className?' '+c1:c1;}
			break;
			case 'remove':
				var rep=o.className.match(' '+c1)?' '+c1:c1;
				o.className=o.className.replace(rep,'');
			break;
			case 'check':
				return new RegExp("(^|\s)" + c1 + "(\s|$)").test(o.className)
			break;
		}
	}

which incorporates all contingencies.


</tip>


--
Chris Heilmann
Blog: http://www.wait-till-i.com
Writing: http://icant.co.uk/
Binaries: http://www.onlinetools.org/



More information about the thelist mailing list