1

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 Answers3

3

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");
p e p
  • 6,593
  • 2
  • 23
  • 32
  • Note that this fully replaces your code, no need for if statements or anything like that, just these two lines. Check out the following article for further explanation on short-circuit boolean evaluation. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators – p e p Sep 14 '14 at 20:59
  • Tough decision...though YMMD's code was very succinct I like the flexibility that the && gives – The One and Only ChemistryBlob Sep 14 '14 at 21:25
2

It's simple. Combine your selector:

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

and

$('#myDiv2:not(:hover)').slideUp();
YMMD
  • 3,730
  • 2
  • 32
  • 43
1

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();
charlietfl
  • 170,828
  • 13
  • 121
  • 150