Check if an element contains a class in JavaScript?

后端 未结 27 2183
面向向阳花
面向向阳花 2020-11-22 09:36

Using plain JavaScript (not jQuery), Is there any way to check if an element contains a class?

Currently, I\'m doing this:

相关标签:
27条回答
  • 2020-11-22 10:03

    This is a bit off, but if you have an event that triggers switch, you can do without classes:

    <div id="classOne1"></div>
    <div id="classOne2"></div>
    <div id="classTwo3"></div>
    

    You can do

    $('body').click( function() {
    
        switch ( this.id.replace(/[0-9]/g, '') ) {
            case 'classOne': this.innerHTML = "I have classOne"; break;
            case 'classTwo': this.innerHTML = "I have classTwo"; break;
            default: this.innerHTML = "";
        }
    
    });
    

    .replace(/[0-9]/g, '') removes digits from id.

    It is a bit hacky, but works for long switches without extra functions or loops

    0 讨论(0)
  • 2020-11-22 10:06
    1. Felix's trick of adding spaces to flank the className and the string you're searching for is the right approach to determining whether the elements has the class or not.

    2. To have different behaviour according to the class, you may use function references, or functions, within a map:

      function fn1(element){ /* code for element with class1 */ }
      
      function fn2(element){ /* code for element with class2 */ }
      
      function fn2(element){ /* code for element with class3 */ }
      
      var fns={'class1': fn1, 'class2': fn2, 'class3': fn3};
      
      for(var i in fns) {
          if(hasClass(test, i)) {
              fns[i](test);
          }
      }
      
      • for(var i in fns) iterates through the keys within the fns map.
      • Having no break after fnsi allows the code to be executed whenever there is a match - so that if the element has, f.i., class1 and class2, both fn1 and fn2 will be executed.
      • The advantage of this approach is that the code to execute for each class is arbitrary, like the one in the switch statement; in your example all the cases performed a similar operation, but tomorrow you may need to do different things for each.
      • You may simulate the default case by having a status variable telling whether a match was found in the loop or not.
    0 讨论(0)
  • 2020-11-22 10:08

    In modern browsers, you can just use the contains method of Element.classList :

    testElement.classList.contains(className)
    

    Demo

    var testElement = document.getElementById('test');
    
    console.log({
        'main' : testElement.classList.contains('main'),
        'cont' : testElement.classList.contains('cont'),
        'content' : testElement.classList.contains('content'),
        'main-cont' : testElement.classList.contains('main-cont'),
        'main-content' : testElement.classList.contains('main-content')
    });
    <div id="test" class="main main-content content"></div>


    Supported browsers

    (from CanIUse.com)


    Polyfill

    If you want to use Element.classList but you also want to support older browsers, consider using this polyfill by Eli Grey.

    0 讨论(0)
  • 2020-11-22 10:08

    If the element only has one class name you can quickly check it by getting the class attribute. The other answers are much more robust but this certainly has it's use cases.

    if ( element.getAttribute('class') === 'classname' ) {
    
    }
    
    0 讨论(0)
  • 2020-11-22 10:08

    Since .className is a string, you can use the string includes() method to check if your .className includes your class name:

    element.className.includes("class1")
    
    0 讨论(0)
  • 2020-11-22 10:10

    I know there a lot of answers but most of these are for additional functions and additional classes. This is the one I personally use; much cleaner and much less lines of code!

    if( document.body.className.match('category-page') ) { 
      console.log('yes');
    }
    
    0 讨论(0)
提交回复
热议问题