开发者

jquery select visible without using :visible

开发者 https://www.devze.com 2023-02-10 15:17 出处:网络
from jquery docs an element is hidden when : An开发者_如何学运维 ancestor element is hidden, so the element is not shown on the page.

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


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.


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.


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.


Try:

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

Result was 2 when I tried it :)

0

精彩评论

暂无评论...
验证码 换一张
取 消