-1

I want to use OR for selectors in jquery.

I write this code:

$("#x").css('display') == 'none' || $("#y").css('display') == 'none'

But refer this answer: https://stackoverflow.com/a/2263976/1407491

I rewrite that code be like this:

$("#x, #y").css('display') == 'none'

This code work fine about this sample code:

<div id="x"></div>
<div id="y"></div>

return false and it's OK.

<div id="x" style="display:none"></div>
<div id="y" style="display:none"></div>

return true and it's OK.

<div id="x" style="display:none"></div>
<div id="y"></div>

return true and it's OK.

But don't work about this sample:

<div id="x"></div>
<div id="y" style="display:none"></div>

return false but it is NOT OK!

Sample code here: http://jsfiddle.net/NabiKAZ/qpquuhxd/

Why is it? and What's clean code?

Community
  • 1
  • 1
Nabi K.A.Z.
  • 9,887
  • 6
  • 59
  • 81
  • 2
    All GETTERS in jQuery only look at the first selected element. You're working with two, and assuming it looks at both, which will of course give unexpected results unless you consider that it only looks at the first. – Kevin B Oct 23 '15 at 21:59
  • @KevinB, and is there shortly code without `||` operator? – Nabi K.A.Z. Oct 23 '15 at 22:01
  • 2
    The only other option would be to use the :visible selector combined with testing the length of the returned collection, but your original solution will be more performant. – Kevin B Oct 23 '15 at 22:02
  • Thanks for your answers, but why you post your comments as a answer?! And so why I got negative vote? – Nabi K.A.Z. Oct 23 '15 at 22:09
  • `$("#x, #y").css("display")` is equal to "block" in your broken example. I guess jquery selectors shouldn't be used for doing logical ORs like that. – James Oct 23 '15 at 22:15
  • I'm not at my desk atm, so being detailed in an answer would be difficult on this tiny phone. Anyone's free to wrap it in an answer, this is common knowledge – Kevin B Oct 23 '15 at 22:16
  • just use each(), like i described in my answer –  Oct 23 '15 at 22:50

1 Answers1

1

If you use multiple selectors, use each:

$("#x, #y").each(function(){     
  if ($(this).css('display') == 'none'){
    $("#cont").append($(this).attr("id")+"'s display is none"); 
  }      
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cont">
  <div id="x">Visible div</div>
  <div id="y" style="display:none">test</div>
</div>
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74