How to check if an element is hidden in jQuery?


How might you test if an HTML element is visible or hidden in the DOM?

Is it possible to toggle the visibility of a HTML element?

2 Answers

You can use the hidden selector:

// Matches all elements that are hidden

And the visible selector:

// Matches all elements that are visible

Often when checking if something is visible or not, jQuery chaining makes this simple.

So if you have a selector and you need to play out some activity on it only if is visible or hidden, you can utilize filter(":visible") or filter(":hidden") trailed by chaining it with the action you want to make.

if statement example:

if ($('#btnUpdate').is(":visible"))
     $('#btnUpdate').animate({ width: "toggle" });   // Hide button

You can do it all in one line:

$('#btnUpdate').filter(":visible").animate({ width: "toggle" });

Please login or create new account to participate in this conversation.