How do I check if an element is hidden in jQuery?
How do I toggle the visibility of an element using .hide(), .show(), or .toggle()?
How do I test if an element is visible or hidden?
How do I toggle the visibility of an element using .hide(), .show(), or .toggle()?
How do I test if an element is visible or hidden?
先自己寫寫看怎麼答,再往下對照重點答案。只存在你這台瀏覽器。
Since the question refers to a single element, this code might be more suitable:
// Checks CSS content for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible");
// The same works with hidden
$(element).is(":hidden");
It is the same as twernt's suggestion, but applied to a single element; and it matches the algorithm recommended in the jQuery FAQ.
We use jQuery's is() to check the selected element with another element, selector or any jQuery object. This method traverses along the DOM elements to find a match, which satisfies the passed parameter. It will return true if there is a match, otherwise return false.
if ( $(element).css('display') == 'none' || $(element).css("visibility") == "hidden"){
// 'element' is hidden
}
The above method does not consider the visibility of the parent. To consider the parent as well, you should use .is(":hidden") or .is(":visible").
For example,
<div id="div1" style="display:none">
<div id="div2" style="display:block">Div2</div>
</div>
The above method will consider
div2visible while:visiblenot. But the above might be useful in many cases, especially when you need to find if there is any error divs visible in the hidden parent because in such conditions:visiblewill not work.