user460114
user460114

Reputation: 1848

jQuery - existing of document parent

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?

Upvotes: 2

Views: 46

Answers (2)

raam86
raam86

Reputation: 6871

Try something like

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

It is probably safer to use

if(parent.$("#toTop").length)){
    //codes
    }

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55750

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) 

Upvotes: 2

Related Questions