[Javascript] Javascript and CSS

Paul Novitski paul at juniperwebcraft.com
Wed Mar 26 20:48:00 CDT 2008


At 3/26/2008 01:41 PM, David Hucklesby wrote:
>Using document.getElementById() - as you suggest - will get you the
>one and only element in the document having that ID. You can then
>see if that element has the class name you want, like this, perhaps:
>
>function hasClass(element, myClass) {
>   var myClass = myClass.replace(/\-/g, "\\-");   // escape hyphens
>   var re = new RegExp("\\b ?"+myClass+"\\b");
>   if (!element.className) return false;
>   return re.test(element.className);
>}



At 3/26/2008 03:12 PM, =?utf-7?Q?Information?= wrote:
>So there is no way that is built into JS to get classes?


As David points out, there very definitely is a way to get the class 
name of a page element using JavaScript.  It isn't built into 
JavaScript, it's built into the DOM (Document Object Model) which 
JavaScript can access.

The class of an element is held in its className property, cf. 
http://developer.mozilla.org/en/docs/DOM:element.className

You can get the class of a known element simply by referencing its className:

         var oExample = document.getElementById('example');
         var sClass = oExample.className;

You can get a list of all the elements on the page with a given class 
by cycling through them:

         var aElements = document.getElementsByTagName('*');

         for (var iElement=0; iElement < aElements.length; iElement++)
         {
                 var sClass = aElements[iElement].className;

                         if (sClass && re.test(sClass)
                         {
                                 aSelected[] = aElements[iElement];
                         }
         }

(Where re is a regular expression such as the ones David and I have suggested.)

Regards,

Paul
__________________________

Paul Novitski
Juniper Webcraft Ltd.
http://juniperwebcraft.com 




More information about the Javascript mailing list