0

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.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Al Grant
  • 2,102
  • 1
  • 26
  • 49

2 Answers2

2

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

bgfvdu3w
  • 1,548
  • 1
  • 12
  • 17
  • I removed the . but still not finding it. – Al Grant Sep 29 '17 at 00:47
  • It looks like the label tags must wrap the select tags in order for this to work https://jsfiddle.net/bigalnz/stezu0cr/11/ – Al Grant Sep 29 '17 at 00:55
  • Yes, it seems to be the case that `closest()` only looks at parents and not at siblings. Unfortunately, while there is a [general sibling combination](https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_selectors), it can only select an element if it follows the first, not if it precedes. If you don't want to nest the `select`s, perhaps [this](https://stackoverflow.com/questions/2310270/jquery-find-closest-previous-sibling-with-class) will help. – bgfvdu3w Sep 29 '17 at 01:01
0

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

Al Grant
  • 2,102
  • 1
  • 26
  • 49