Is there an “exists” function for jQuery?

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

    Here is the complete example of different situations and way to check if element exists using direct if on jQuery selector may or may not work because it returns array or elements.

    var a = null;
    
    var b = []
    
    var c = undefined ;
    
    if(a) { console.log(" a exist")} else { console.log("a doesn't exit")}
    // output: a doesn't exit
    
    if(b) { console.log(" b exist")} else { console.log("b doesn't exit")}
    // output: b exist
    
    if(c) { console.log(" c exist")} else { console.log("c doesn't exit")}
    // output: c doesn't exit
    

    FINAL SOLUTION

    if($("#xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
    //output : xusyxxs doesnn't exist
    
    if($(".xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
        //output : xusyxxs doesnn't exist
    

    Demo

    console.log("existing id", $('#id-1').length)
    console.log("non existing id", $('#id-2').length)
    
    console.log("existing class single instance", $('.cls-1').length)
    console.log("existing class multiple instance", $('.cls-2').length)
    console.log("non existing class", $('.cls-3').length)
    
    

提交回复
热议问题