Aug 16

I have previously used the following to check if an element belongs to a certain CSS class:

JavaScript:
  1. if(myElement.className == 'colorful-class'){
  2.    takeAction();
  3. }

This method fails when an element bears two or more classes (which I have been using more frequently). A better method is to use JavaScript regular expressions methods to find whether the class attribute contains your class. Visit regular-expressions.info for a crash course on regular expressions if you are unfamiliar - they are fabulous and you must learn to use them.

There are several JavaScript RegExp methods we can implement. The best for this purpose is the test() method.

JavaScript:
  1. if(/colorful-class/.test(myElement.className)){
  2.    takeAction();
  3. }

With the following HTML, the aforewritten regular expression will return true. Using the JS equality operator would return false.

HTML:
  1. <p class="textful colorful-class">
  2. A textfully classed paragraph.
  3. </p>

Leave a Reply




  • Meta