Joy
Joy

Reputation: 41

How can I test if an element is already visible?

In the HTML code, I use jQuery to hide or display an element having an ID. How can I test if an element is already visible?

For example, we use show() to display an element having an ID. But before calling show(), I need to test whether show() has been already used for that ID then how to compare?

Upvotes: 0

Views: 82

Answers (2)

Surreal Dreams
Surreal Dreams

Reputation: 26380

If the element is visible, show() won't do anything, so it's pretty low risk. However, you can use the :visible or :hidden selector to find visible elements.

$('#myId:visible').hide();

$('#myId:hidden').show();

Using this in your selector, you can just fire off the show and hide methods and not worry about what is visible or not, because if you try to hide a :hidden element, you won't select anything so you won't do anything.

Upvotes: 2

Stephen
Stephen

Reputation: 18964

$('#element').is(':hidden'); // boolean

Upvotes: 2

Related Questions