5

I am trying to populate an array in JavaScript using jQuery. I have some <div> elements in a <section> and I only want the <div> elements that are visible (via CSS property display: block) to be added to the array.

HTML:

<section id="container">
    <div>shows up 1</div>
    <div style="display:none">doesn't show 2</div>
    <div>shows up 3</div>
    <div style="display:none">doesn't show 4</div>
    <div style="display:none">doesn't show 5</div>
    <div>shows up 6</div>
    <div>shows up 7</div>
    <div>shows up 8</div>
    <div style="display:none">doesn't show 9</div>
    <div>shows up 10</div>
</section>

JavaScript / jQuery

var mainList = $("#container div");

This currently gets ALL <div> elements regardless of their display. Is there some kind of filter I can put onto this call to get only the elements that are visible? It should only return the 6 <div> elements that say "shows up" in them.

Fiddle: http://jsfiddle.net/259chbj4/

Note: For this, I can't use a class that has display: none. I am looking for a solution that only modifies the JavaScript.

Etheryte
  • 20,940
  • 10
  • 58
  • 98
AlbatrossCafe
  • 1,573
  • 5
  • 22
  • 44
  • 1
    possible duplicate of [Checking if an element is hidden](http://stackoverflow.com/questions/178325/checking-if-an-element-is-hidden) – abl Sep 11 '15 at 18:15

2 Answers2

4

You can simply use the :visible selector.

$("#container div:visible");
Etheryte
  • 20,940
  • 10
  • 58
  • 98
3

try:

 var mainList = $('#container').find("div :visible");
Leo
  • 655
  • 2
  • 9
  • 24