Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate a JavaScript array with only the divs that have display:block?

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.

like image 971
AlbatrossCafe Avatar asked Sep 11 '15 18:09

AlbatrossCafe


2 Answers

You can simply use the :visible selector.

$("#container div:visible");
like image 75
Etheryte Avatar answered Nov 01 '22 20:11

Etheryte


try:

 var mainList = $('#container').find("div :visible");
like image 3
Leo Avatar answered Nov 01 '22 18:11

Leo