Is there an “exists” function for jQuery?

Question!

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
}

Is there is a more elegant way to approach this? Perhaps a plugin or a function?



Answers

Use the following syntax to check if the element actually exists using jQuery.

let oElement = $(".myElementClass");
    if(oElement[0]) {
      // Do some jQuery operation here using oElement
    }
    else {
      // Unable to fetch the object
    }


Here is the complete exmple 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 element depending on selector so if you use Id selector .length property will throw error.

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

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

if($("#xysyxxs")){ 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 : Uncaught TypeError: Cannot read property 'length' of null(…)

FINAL SOLUTION

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


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.



This video can help you solving your question :)
By: admin