ntan
ntan

Reputation: 2205

jquery select visible without using :visible

from jquery docs an element is hidden when : An ancestor element is hidden, so the element is not shown on the page.

I have a hidden div and inside paragraphs that can be either hidden or visible

<div id="wrapper"> <-- this is hidden -->
    <p class="myclass" style=">display:none">text</p> 
    <p class="myclass">text</p> 
    <p class="myclass" style=">display:none">text</p> 
    <p class="myclass">text</p> 
</div>

So any selection $(".myclass:visible") fails because wrapper is hidden

Is there any other way to check if are visible elements inside wrapper and count them.

For example check if element has class myclass and css display:none is one solution i guess but any tries from me are failed.

Any help appreciated

Upvotes: 3

Views: 5816

Answers (4)

Felix Kling
Felix Kling

Reputation: 816334

The only way I see is to add a custom class that hides elements (instead of inline style):

.hidden {
    display: none;
}

<div id="wrapper"> <-- this is hidden -->
    <p class="myclass hidden"text</p> 
    <p class="myclass" >text</p> 
    <p class="myclass hidden">text</p> 
    <p class="myclass" >text</p> 
</div>

Then you can count the "visible" ones with $('.myclass:not(.hidden)').length.


Update:

If you actually only have to find the elements which display property is not none, .filter() could do the job:

var count = $('.myclass').filter(function() {
    return this.style.display !== "none";    
}).length;

Of course this won't work if some elements have display:none set by you and not by the UI tabs plugin. But it might be sufficient in your situation.

Upvotes: 7

cam8001
cam8001

Reputation: 1641

You can check the display property directly, eg:

$('#wrapper p.myclass').each(function(){
 alert($(this).attr('style'));
}

will show you the value of the style attribute.

you can also do

this.style.display to access the display property directly.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074148

I'd use Felix's way.

But if you really want an alternative without changing your markup, this should work:

var wrapper, visibles;
wrapper = $("#wrapper");
wrapper.show();
visibles = wrapper.find(":visible");
wrapper.hide();

Live example

As long as you don't have a yield in there (setTimeout, etc.), odds are high the browser won't actually show anything during the brief interval in which the wrapper is visible.

Upvotes: 2

Brian
Brian

Reputation: 8616

Try:

alert ( $("#wrapper .myclass:visible").size());

Result was 2 when I tried it :)

Upvotes: -1

Related Questions