JQuery .hasClass for multiple values in an if statement

后端 未结 10 846
名媛妹妹
名媛妹妹 2020-12-02 18:14

I have a simple if statement as such:

if ($(\'html\').hasClass(\'m320\')) {

// do stuff 

}

This works as expected. However, I want to add

10条回答
  •  没有蜡笔的小新
    2020-12-02 18:49

    For anyone wondering about some of the different performance aspects with all of these different options, I've created a jsperf case here: jsperf

    In short, using element.hasClass('class') is the fastest.

    Next best bet is using elem.hasClass('classA') || elem.hasClass('classB'). A note on this one: order matters! If the class 'classA' is more likely to be found, list it first! OR condition statements return as soon as one of them is met.

    The worst performance by far was using element.is('.class').

    Also listed in the jsperf is CyberMonk's function, and Kolja's solution.

提交回复
热议问题