jquery selection of elements with no visible children

Glen picture Glen · May 8, 2009 · Viewed 9.1k times · Source

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

Answer

Jed Schmidt picture Jed Schmidt · May 8, 2009

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() )