Is there an “exists” function for jQuery?

前端 未结 30 3752
野性不改
野性不改 2020-11-21 04:52

How can I check the existence of an element in jQuery?

The current code that I have is this:

if ($(selector).length > 0) {
    // Do something
}
<         


        
30条回答
  •  耶瑟儿~
    2020-11-21 05:21

    No need for jQuery (basic solution)

    if(document.querySelector('.a-class')) {
      // do something
    }
    

    Much more performant option below(notice lack of a dot before a-class).

    if(document.getElementsByClassName('a-class')[0]) {
      // do something
    }
    

    querySelector uses a proper matching engine like $() (sizzle) in jQuery and uses more computing power but in 99% cases will do just fine. The second option is more explicit and tells the code exactly what to do. It's much faster according to jsperf https://jsperf.com/getelementsbyclassname-vs-queryselectorall/25

提交回复
热议问题