Ron Harlev
Ron Harlev

Reputation: 16693

Detect if html parent is hidden

I would like to detect when a specific HTML element on the page becomes hidden. This usually happens due to a parent element (maybe few levels up) becoming hidden. Is there a simple way to detect this. Or do I need to traverse the DOM and check each parent?

Upvotes: 15

Views: 10487

Answers (4)

treeface
treeface

Reputation: 13351

Like this:

alert($('#test1').is(":visible"));
#test {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
  <div id="test1">
    test
  </div>
</div>

View on JSFiddle

Upvotes: 7

Matti Virkkunen
Matti Virkkunen

Reputation: 65136

$(foo).is(":hidden")

can figure that out for you in current jQuery versions.

Upvotes: 18

AutoSponge
AutoSponge

Reputation: 1454

jQuery uses offsetHeight. That works in most browsers. But you can check that without jQuery too.

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630509

You can just check if it's :hidden, for example:

$(".selector:hidden").length > 0
//or
$(".selector").is(":hidden")

This works if the parent is hidden, or any parent, or the element directly...as long as the element itself has no dimensions, it's :hidden.

Upvotes: 9

Related Questions