Is there an “exists” function for jQuery?

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

    $("selector") returns an object which has the length property. If the selector finds any elements, they will be included in the object. So if you check its length you can see if any elements exist. In JavaScript 0 == false, so if you don't get 0 your code will run.

    if($("selector").length){
       //code in the case
    } 
    

提交回复
热议问题