简体   繁体   中英

jQuery to find parent label

I have this HTML fragment:

<div class="form-group">
  <div class="col-sm-1"></div>
  <label for="allquestion4" class="col-sm-6 control-label label-red">Question</label>
  <div class="col-sm-1"></div>
  <div class="col-sm-3">
    <select size="2" class="selectpicker" id="allquestion4" title="Choose">
      <option value="0">No</option>
      <option value="1">Yes</option>
    </select>
  </div>
  <div class="col-sm-1"></div>
</div>

Why is the label not being found by the following jQuery:

$(this).closest('label').hasClass('.label-red');

Where $(this) is the select picker.

UPDATE

Try this fiddle.

Remove the . from hasClass('.label-red') . It wants the name of the class not a CSS selector.

There is an error in the original JQuery selector as pointed out by @Mark remove the . from the hasClass('.label-red') secondly the selector needs a parent so the html needs to be modified so that the <label> tags wrap the <select> thus:

<label class="col-sm-6 control-label label-red">Question
    <select size="2" class="selectpicker" id="allquestion4" title="Choose">
        <option value="0">No</option>
        <option value="1">Yes</option>
    </select>
</label>

Or if the html is kept the same navigate to the parent form-group and then find like this:

$(this).closest('.form-group').find('select').hasClass('label-red')

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