简体   繁体   中英

Show parent DIV if children spans have class

I'm trying to figure out why this is not working. I have a div that I'd like to be toggled open if it has one or more span children with a class of .reqiredError .

See JSFiddle

<div class="more-content" style="display:none;">
    <div class="col-xs-5 form-group">
        <label for="dua-status">
            Status: 
            <span class="required">*</span> 
            <span class="requiredError">Required Field</span>
        </label>
        <select id="dua-status">
            <option>Open</option>
        </select>
    </div>
</div>
$(document).ready(function() {
    if ($('span').hasClass('requiredError')) {
        $(this).closest().parent('div.more-content').fadeIn(0);
    }
});

You do not need the if statement.

Rather, target them with a selector using :has() . The advantage of this is you do not have to navigate up to parent as the context will be the parent div that has those spans

 $(document).ready(function() { $('div.more-content:has(.requiredError)').fadeIn(0); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="more-content" style="display:none;"> <div class="col-xs-5 form-group"> <label for="dua-status">Status: <span class="required">*</span> <span class="requiredError">Required Field</span> </label> <select id="dua-status"> <option>Open</option> </select> </div> </div> 

You can find the target element then use .closest() find the the target ancestor element

 $(document).ready(function() { $('.requiredError').closest('.more-content').fadeIn(0); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="more-content" style="display:none;"> <div class="col-xs-5 form-group"> <label for="dua-status">Status: <span class="required">*</span> <span class="requiredError">Required Field</span> </label> <select id="dua-status"> <option>Open</option> </select> </div> </div> 

closest vs has

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM