Is there an “exists” function for jQuery?

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

    You can save a few bytes by writing:

    if ($(selector)[0]) { ... }
    

    This works because each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get the first item from the array. It returns undefined if there is no item at the specified index.

提交回复
热议问题