Check if an element contains a class by regex with classList

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()

Please advise.

Answers:

Answer

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;
    }
}
Answer
var items = document.getElementsByClassName('items-list')[0];
  for (var i = 0, len = items.children.length; i < len; i++) {
    if (/item-/.test(items.children[i].className)) {
      console.log(items.children[i].className);
      // or doSomething();
  }
}

http://jsfiddle.net/tcs6b/ perhaps?

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.