Jquery selector for MISSING element child

I need help creating a jquery selector to return elements that lack a specific child element.

Given the following HTML snippet:

    <div id="rack1" class="rack">
    <span id="rackunit1" class="rackspace">
        <span id="component1">BoxA</span>
        <span id="label1">Space A</span>
    </span>
    <span id="rackunit2" class="rackspace">
        <span id="label2">Space B</span>
    </span>
    <span id="rackunit3" class="rackspace">
        <span id="component2">BoxA</span>
        <span id="label3">Space C</span>
    </span>
</div>
<div id="rack2" class="rack">
    <span id="rackunit4" class="rackspace">
        <span id="component3">BoxC</span>
        <span id="label4">Space D</span>
    </span>
    <span id="rackunit5" class="rackspace">
        <span id="label5">Space E</span>
    </span>
    <span id="rackunit6" class="rackspace">
        <span id="component4">BoxD</span>
        <span id="label6">Space F</span>
    </span>
</div>

Find for me rack racks with an NO component. So far I have: $ (". Rack.rackspace") to get all ranges of racks, not sure how to exclude those that have a range of components, or select only those that don’t ...

+5
source share
2 answers

I think the following should work:

$(".rack .rackspace:not(:has(span[id^=component]))"). ...

DEMO: http://jsfiddle.net/WbCzj/

+8
source

You can use .filter():

$('.rack .rackspace').filter(function() {
    return $(this).find('span[id^="component"]').length === 0;
});
+3
source

All Articles