Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 457
Sergei Basharov Avatar asked Jan 27 '14 20:01

Sergei Basharov


2 Answers

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;
    }
}
like image 112
Oriol Avatar answered Sep 23 '22 00:09

Oriol


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?

like image 29
JGrubb Avatar answered Sep 20 '22 00:09

JGrubb