jQuery – existing of document parent-Collection of common programming errors

Found a few similar articles, but can’t seem to get anything to work.

We have this code as follows:

parent.$("#toTop").trigger("click");

However, we need to check for the existence of the parent element as it is throwing an error in some cases where dom setup is different:

parent.$(...) is null

How would I do that?

  1. Try something like

    if(parent.$("#toTop")){//Not true if is undefined / null 
    //codes
    }
    

    It is probably safer to use

    if(parent.$("#toTop").length)){
        //codes
        }
    
  2. if( parent && parent.$("#toTop")) {
        parent.$("#toTop").trigger("click");
    }
    

    If you are specifically looking only for the parent you can use this

    if( parent )
    

    There might be a case when the parent gives you a empty selector. So you can check for the length in such cases..

    if(parent.length) 
    

Originally posted 2013-11-09 19:43:08.