Check if an element contains a regex class with class List
I have a simple list of items that look 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 choose a list
items = document.getElementsByClassName('items-list')[0]
Finally, inside the loop, for..inI want to extract the class name 'item-*'. Since I want to do this without jQuery or other libraries, I wonder how I can do this in the most elegant way, something like
if (item.classList.contains('item-.*'))
do_something()
Please inform.
+4
2 answers
You can check if some(ES5) matches regExp class:
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 the arrow functions , you can simplify this for
if(item.className.split(' ').some(c => /item-.*/.test(c)))
do_something()
/* or */
if([].some.call(item.classList, c => /item-.*/.test(c)))
do_something()
, , , :
for (var i=0, l=item.classList.length; i<l; ++i) {
if(/item-.*/.test(item.classList[i])) {
do_something();
break;
}
}
+4