Is there an “exists” function for jQuery?

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

    In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 means false, everything else true. So you could write:

    if ($(selector).length)
    

    You don't need that >0 part.

提交回复
热议问题