Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery selection of elements with no visible children

Here's my goal: do something on an element, an <optgrooup>, if all of its children are invisible.

My code below outlines the in red if it has any invisible children. But I want to do so only if all the children are invisible. If the element has any children that are visible, then don't highlight it.

How can I tweak the jQuery selector to do that?

Thanks in advance.

<select multiple="multiple" name="availableInstanceId" id="availableInstanceId">
<optgroup label="Option Group 1">
   <option >visible item 1</option>
   <option >visible item 2</option>
</optgroup>
<optgroup label="Option Group 2 - Should be highlighted">
   <option style="display:none;">invisible A</option>
   <option style="display: none">invisible B</option>
</optgroup>

<optgroup label="Option Group 3 - Should not be highlighted">
  <option >visible C</option>
  <option style="display: none">invisible D</option>
</optgroup></select>

<script type="text/javascript">
var filterOptions = function(e) {
  // Goal: highlight the <optgroup>'s that have *only* invisible children
  $( '#availableInstanceId > * > *:hidden').parent().css("border","3px solid red");
} 
$(document).ready(function() {
  filterOptions();
});
</script>

Screenshot of image here: http://img144.imageshack.us/img144/556/selectexample.gif

like image 220
Glen Avatar asked May 08 '09 19:05

Glen


People also ask

Can jQuery find hidden elements?

You can simply use the jQuery :visible or :hidden selector to select all the visible or hidden elements in an HTML page. The jQuery :visible selector considered an element visible if they consume space in the document.

How do you hide a div with kids?

If you want the children to hide, either set them to be visibility: hidden too, or use display: none on the parent element. So, as Kyle pointed out, you can use $('#parent_div'). toggle(); , which will easily apply a display: none to #parent_div .

How check div is visible or not in jQuery?

You can use .is(':visible') selects all elements that are visible.

Which jQuery filter can be used to check if element is visible?

Given a HTML document and the task is to check the element is visible or not using jQuery :visible selector. The :visible selector can be used with . toggle() function to toggle the visibility of an element.


1 Answers

Assuming you want to exclude elements with no child elements:

 $(":has(*):not(:has(:visible))")

Working example.

UPDATE: This has much better performance than my original answer:

$(":hidden").parent().not( $(":visible").parent() )
like image 149
Jed Schmidt Avatar answered Oct 21 '22 07:10

Jed Schmidt