Check if an element contains a class by regex with classList
dom, html, javascript
Solution
You can check if `some` (ES5) class matches your regExp:
if(item.className.split(' ').some(function(c){ return /item-.*/.test(c); }))
do_something()
/* or */
if([].some.call(item.classList, function(c){ return /item-.*/.test(c); }))
do_something()
Or, in ES6, using arrow functions, you can simplify that to
if(item.className.split(' ').some(c => /item-.*/.test(c)))
do_something()
/* or */
if([].some.call(item.classList, c => /item-.*/.test(c)))
do_something()
But of course, if you want maximum performance, use a loop:
for (var i=0, l=item.classList.length; i<l; ++i) {
if(/item-.*/.test(item.classList[i])) {
do_something();
break;
}
}
Problem
I have a simple list of elements looking like this: ``` <ul class="items-list"> <li class="item item-1"></li> <li class="item item-2"></li> <li class="item item-3"></li> <li class="item item-4"></li> </ul> ``` I select the list by ``` items = document.getElementsByClassName('items-list')[0] ``` Finally inside a `for..in` loop I want to extract class name that is `'item-*'`. As I want to make it without jQuery or other libraries, I wonder how I can do it in the most elegant way, something like ``` if (item.classList.contains('item-.*')) do_something() ```