Al Grant
Al Grant

Reputation: 2354

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.

Upvotes: 0

Views: 1503

Answers (2)

Al Grant
Al Grant

Reputation: 2354

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

Upvotes: 0

bgfvdu3w
bgfvdu3w

Reputation: 1675

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

Upvotes: 2

Related Questions