Mingle Li
Mingle Li

Reputation: 1350

JavaScript - If statement in if statement condition

I want to check for an element's existence in the if statement condition, and if so then use the element as part of the comparison. Something like this:

if( if($(".element").length > 0) { $.contains( $(".element")[0], $("[ele]")[0] )} ) {...

I know I could just nest if statements, like:

if($(".element").length > 0) {
    if($.contains( $(".element")[0], $("[ele]")[0] )) {....

But is there a shorter way to do this? Can if statements be used in another if statement's condition like this in some way?

Upvotes: 0

Views: 582

Answers (2)

hackerrdave
hackerrdave

Reputation: 6706

You can use the && operator to chain both of your conditions:

if($(".element").length > 0 && $.contains( $(".element")[0], $("[ele]")[0] )) {

If the the first condition fails (code prior to &&), it will short out and not execute the second condition.

Upvotes: 1

chridd
chridd

Reputation: 161

You can use the && (and) operator for that. If the thing on the left side of the && is false, then it doesn't evaluate the right side of &&, so you don't have to worry about any errors from the element not existing. (This is called short-circuit evaluation, and || (or) does a similar thing, except || doesn't evaluate the right side if the left side it true.) So

if($(".element").length > 0 && $.contains( $(".element")[0], $("[ele]")[0] )) ...

It's not necessary here, but if you want an if-else inside an expression, you can use the ?: (ternary conditional) operator. condition ? a : b is like if(condition) a else b, except it's actually an expression, so for instance, x = (condition ? a : b) is the same as if(condition) x = a; else x = b;.

Upvotes: 0

Related Questions