Nick G
Nick G

Reputation: 1973

jQuery selector that gets all parent elements with less than n children

I have a table that can have a variable amount of <td> elements in each row, but with a max of 3 <td> elements per row. Say I wanted to select the rows with less than 3 <td> elements and assign them to a variable, is there a way I can select these rows with just jQuery? I know I can use something where I iterate through each row, like so:

var rows = $("tr").filter(function() {
  return $(this).children().length < 3
});

rows.css("background-color", "blue");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
    <tr>
      <td>1</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
    </tr>
  </tbody>
</table>

Is there a way I can do the same with just jQuery selectors and methods (i.e. .siblings() or .parents())?

Here's a JSFiddle of the example I gave. I've looked for a similar question but couldn't find anything like this, so I'm hoping someone will have some ideas if this is possible.

Upvotes: 2

Views: 96

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115282

Use combination of :not() , :has() and :eq() pseudo-class selectors.

var rows = $("tr:not(:has(:eq(2)))");

rows.css("background-color", "blue");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
    </tr>
    <tr>
      <td>1</td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
    </tr>
  </tbody>
</table>


FYI : Depending on your need you can use :nth-child() or :nth-of-type() instead of :eq() method.

Upvotes: 6

Related Questions