Is there an “exists” function for jQuery?

前端 未结 30 3007
野性不改
野性不改 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:13

    You don't have to check if it's greater than 0 like $(selector).length > 0, $(selector).length it's enough and an elegant way to check the existence of elements. I don't think that it is worth to write a function only for this, if you want to do more extra things, then yes.

    if($(selector).length){
      // true if length is not 0
    } else {
      // false if length is 0
    }
    

提交回复
热议问题