Aman Nagarkoti Aman Nagarkoti - 22 days ago 6
jQuery Question

jquery selector for <select> having exactly 2 children

I want a jquery selector which selects all having exactly 2 options in it.

I tried every thing but unable to find any suitable answer.

Answer

CSS doesn't have a selector construct for counting the number of children, so you won't get just a single selector for this. Instead, you can use filter:

var selectsWithTwoOptions = $("select").filter(function() {
    return this.options.length == 2;
});

Or in ES2015:

let selectsWithTwoOptions = $("select").filter(() => this.options.length == 2);

Example:

var selectsWithTwoOptions = $("select").filter(function() {
    return this.options.length == 2;
});
selectsWithTwoOptions.css({
  color: "green",
  fontWeight: "bold"
});
select {
  width: 12em;
}
<div>
  <select>
    <option>I have one option</option>
  </select>
</div>
<div>
  <select>
    <option>I have two options</option>
    <option>two</option>
  </select>
</div>
<div>
  <select>
    <option>I have three options</option>
    <option>two</option>
    <option>three</option>
  </select>
</div>
<div>
  <select>
    <option>I have four options</option>
    <option>two</option>
    <option>three</option>
    <option>four</option>
  </select>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>