JavaScript Regex Comparisons
JavaScript August 16th, 2007I have previously used the following to check if an element belongs to a certain CSS class:
-
if(myElement.className == 'colorful-class'){
-
takeAction();
-
}
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.
-
if(/colorful-class/.test(myElement.className)){
-
takeAction();
-
}
With the following HTML, the aforewritten regular expression will return true. Using the JS equality operator would return false.
-
<p class="textful colorful-class">
-
A textfully classed paragraph.
-
</p>
Popularity: 10% [?]









Recent Comments