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

1.4k Views Asked by At

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?

3

There are 3 best solutions below

2
On BEST ANSWER

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");
1
On

You can't chain methods after using one of the methods as a getter. Since hasClass() is strictly a getter it is one of the few methods in the jQuery API that can never be chained.

Examples of other getters you can't chain to:

$(selector).val() ; /* returns string or array*/
$(selector).css('color'); /* with only one argument will return a value and not the element collection */

When used as setters both of the above methods can be chained as they will return the element collection referenced by selector:

$(selector).val(400).addClass('someClass') ;
$(selector).css('color','blue').somePlugin();
5
On

It's simple. Combine your selector:

$('#myDiv1.myClass1').hide();

and

$('#myDiv2:not(:hover)').slideUp();