jqueryconditional-statementsjquery-chaining

Is it possible to chain hasClass() or is() in a conditional statement?


I noticed in my site's code that I have a lot of the following types of conditional statements:

//Example 1
if ($("#myDiv1").hasClass("myClass1")) {
    $("#myDiv1").hide();
}

//Example 2
if (!$("#myDiv2").is(":hover")) {
    $("#myDiv2").slideUp("slow");
}

The obvious way of tidying this up a bit is as follows:

//Example 1
var e1 = $("#myDiv1");
if (e1.hasClass("myClass1")) {
    e1.hide();
}

//Example 2
var e2 = $("#myDiv2");
if (!e2.is(":hover")) {
    e2.slideUp("slow");
}

However, I was wondering is I could somehow chain the functions despite the if statement. I tried these two lines of code (didn't think it would work and it didn't);

//Example 1
var e1 = $("#myDiv1");
if (e1.hasClass("myClass1").hide()); //Attempt1

e1.hasClass("myClass1").hide(); //Attempt2

Is there any way to chain through the conditional when the DOM element is the same in both the if statement and the argument for the if statement?


Solution

  • One way of rewriting this to take up less code is as follows. This style takes advantage of the way JavaScript evaluates boolean statements and is sometimes referred to as 'short-circuiting'. Basically the second part of each line (after the &&) will only execute if the first part is true.

    $("#myDiv1").hasClass("myClass1") && $("#myDiv1").hide();
    !$("#myDiv2").is(":hover") && $("#myDiv2").slideUp("slow");