简体   繁体   中英

jquery add class to closest parent

I have a form, and some the fields are set inside 3 groups of collapsible divs, I wan't after the validation that if any field has errors the parent div receive a class to unfold it.

<div class="panel-group" id="fields_panel">
  <div class="panel panel-primary">
    <div id="basic_info_fields" class="panel-collapse collapse in"> <!-- add class "in" -->>
      <div class="panel-body">
        <div class="row clearfix">
          <div class="col-md-12 m-b-0">
            <div class="form-group">
              <div class="form-line error"> <!-- if this div has "error" -->
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

I have two more panels with the same structure, eacho one with a couple of fields, I'm trying to find if any form-line has error and append to the panel-collapse parent the class in to unfold it.

Right now I have the following jquery code:

$(function () {
    var elem = $('.panel').find('.form-line');
    if (elem.hasClass('error')) {
        elem.closest('.panel-collapse').addClass('in');
    };
});

But it apply the in class to all panel-collapse . What should I do to apply it only to the top level parent that have a child element with that class, and not to all parents?

Your hasClass won't work as elem is an array of jQuery objects - not just one.

Why do you need it - why not just include the class in your selector:

$('.panel').find('.form-line.error').closest('.panel-collapse').addClass('in');

This also stops you looping through elements in the array that doesn't have the class thus improving efficiency

Use following code:

$('.panel').find('.form-line.error').each(function(){
    $(this).closest('.panel-collapse').addClass('in');
});

$(this) refers to the specified element which has the error class.

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