2

In my JavaScript I use the css selector [style="display:none"] and the code works in Chrome, Firefox, Opera and Safari (on Windows) as expected.

However in Internet Explorer (version 11) it works unfortunately wrong.

For testing:
Just click on the buttons (e.g. #visible_elements_count) in Chrome and then click on the buttons in Internet Explorer. You will experience different return values.

HTML:

<section>
    <ul>
        <li>visible Element</li>
        <li style="display:none">invisible Element</li>
        <li>visible Element</li>
    </ul>
</section>

<button id="all_elements_count">all elements</button>
<button id="visible_elements_count">visible elements</button>
<button id="invisible_elements_count">invisible elements</button>

<!-- JAVASCRIPTS -->
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
    $("#all_elements_count").click(function () {
        var counter = $("section ul li").length;
        alert(counter);
    });

    $("#visible_elements_count").click(function () {
        var counter = $("section ul li:not([style='display:none'])").length;
        alert(counter);
    });

    $("#invisible_elements_count").click(function () {
        var counter = $("section ul li[style='display:none']").length;
        alert(counter);
    });
</script>

Sources: I read everything about selectors! and still can not solve this problem.

Any help is appreciated!

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
stylesenberg
  • 519
  • 3
  • 16
  • take a look at [Article StackoverFlow](http://stackoverflow.com/questions/15924751/check-if-a-element-is-displaynone-or-block-on-click-jquery) – Paul Mar 11 '15 at 09:45

2 Answers2

3

You should use :hidden, :visible with use of .filter():

    $("#all_elements_count").click(function () {
        var counter = $("section ul li").length;
        alert(counter);
    });

    $("#visible_elements_count").click(function () {
        var counter = $("section ul li").filter(':visible').length;
        alert(counter);
    });

    $("#invisible_elements_count").click(function () {
        var counter = $("section ul li").filter(':hidden').length;
        alert(counter);
    });
Jai
  • 74,255
  • 12
  • 74
  • 103
  • 1
    This worked! Could you explain why using the JQuery attribute selector [style='display:none'] led to an error? – stylesenberg Mar 11 '15 at 10:05
  • @stylesenberg it might be possible that IE behaves differently when working with attributes. I guess that's the way it might be implemented in the IE. – Jai Mar 11 '15 at 10:08
1

You should use jQuery :visible & :hidden pseudo selectors:

var counter = $("section ul li:visible").length;

var counter = $("section ul li:hidden").length;

For better performance, see @Jai's answer.

A. Wolff
  • 74,033
  • 9
  • 94
  • 155