Check if an element contains a class in JavaScript?

后端 未结 27 3083
面向向阳花
面向向阳花 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: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.

提交回复
热议问题