Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js - shorten multiple conditions

I have an if statement as below.

if($("#a").css("display") == "none" && $("#b").css("display") == "none" && $("#c").css("display") == "none" && $("#d").css("display")  == "none" && $("#e").css("display") == "none" && $("#f").css("display") == "none")

Is there anyway to shorten this line?

like image 215
Lewis Avatar asked Nov 20 '25 01:11

Lewis


2 Answers

Sure, something like

if ( ! $('#a, #b, #c, #d, #e, #f').is(':visible') ) { .... }

returns true if all are hidden

like image 94
adeneo Avatar answered Nov 21 '25 13:11

adeneo


You can put all the ids to be checked in an Array and then use Array.prototype.every function, like this

var ids = ["a", "b", "c", "d", "e", "f"];
if (ids.every(function(id){return $("#" + id).css("display") == "none";})){
   ...
}

Note: You can decide at runtime, which ids have to be checked, without modifying the condition.

Note 1: As @Jon Dvorak suggests, it was introduced in ES5 only. You can check whether it is compatible with your environment or not with this compat table

like image 27
thefourtheye Avatar answered Nov 21 '25 15:11

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!