Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore visibility of outer elements and select the first visible child element in a jQuery selector

HTML:

<div class="outer">
  <div id="inner1" class="inner" style="display: none"></div>
  <div id="inner2" class="inner"></div>
  <div id="inner3" class="inner"></div>
</div>

JavaScript (fiddle):

var $first_visible = $("div.inner:visible:first");

This returns the first visible inner div, which is inner2.

However, as soon as the outer div is hidden (let's say I want to fade it in at some later time):

<div class="outer" style="display: none">
  <div id="inner1" class="inner" style="display: none"></div>
  <div id="inner2" class="inner"></div>
  <div id="inner3" class="inner"></div>
</div>

all inner divs are considered hidden and the selector does not return inner2 any more.

How would I need to modify my jQuery selector to ignore the container's visibility?

like image 220
Heinzi Avatar asked Jan 22 '16 16:01

Heinzi


2 Answers

MDN says:

When you use none, all descendant elements also have their display turned off. The document is rendered as though the element doesn't exist in the document tree.

Hence, whatever the HTML elements are child to the parent element will not be rendered in the HTML page.

And moreover, whatever styles that has been applied on the parent element will not be rendered in HTML page.

In order to achieve what you want and if you consider that your HTML element should be in the document tree then try using CSS visibility property. For example:

<div class="outer" style="visibility: hidden">
  <div id="inner1" class="inner" style="display: none"></div>
  <div id="inner2" class="inner" style="visibility: visible"></div>
  <div id="inner3" class="inner"></div>
</div>

JS Fiddle

like image 87
Umesh Avatar answered Sep 22 '22 12:09

Umesh


As adeneo said, once its hidden, there isnt much you can do.

However, you can check before hand, show it regardless, then hide it again if it was hidden

var wasVisible = $(".outer").is(':visible');

$(".outer").show();

var $first_visible = $("div.inner:visible:first");

if (!wasVisible) {
  $(".outer").hide();
}

console.log($first_visible.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="outer" style="display: none">
  <div id="inner1" class="inner" style="display: none"></div>
  <div id="inner2" class="inner"></div>
  <div id="inner3" class="inner"></div>
</div>
like image 27
AmmarCSE Avatar answered Sep 22 '22 12:09

AmmarCSE