I have the following elements:
No need of loop over each of the element and each of the class to check it it exists on the element.
You can use regex as follow:
Demo
var arr = ['nine', 'ten', 'eleven'];
var classes = '\\b(' + arr.join('|') + ')\\b',
regex = new RegExp(classes, 'i');
$('div').each(function() {
var elClasses = ' ' + $(this).attr('class').replace(/\s+/, ' ') + ' ';
if (regex.test(elClasses)) {
$(this).addClass('valid');
}
})
div {
color: red;
}
.valid {
color: green;
}
Invalid
Valid Ten
Invalid
Invalid
Valid 11
Valid 9
REGEX EXPLANATION
\b: Will match the word boundary|: Works as OR in regexarr.join('|'): Will join all the elements of array using | to join(): Capturing Group. In this case used for matching one of the classSo, regex in above case will be
/\b(nine|ten|eleven)\b/