Check if element contains any of the class from array

后端 未结 6 1143
一整个雨季
一整个雨季 2021-01-17 06:28

I have the following elements:

6条回答
  •  庸人自扰
    2021-01-17 07:31

    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

    1. \b: Will match the word boundary
    2. |: Works as OR in regex
    3. arr.join('|'): Will join all the elements of array using | to join
    4. (): Capturing Group. In this case used for matching one of the class

    So, regex in above case will be

    /\b(nine|ten|eleven)\b/
    

提交回复
热议问题