Stephen Gornick
Stephen Gornick

Reputation: 392

JQuery selector to match table having N rows

I have a div with two tables. I want to select the rows from only the one table having N rows.

In XPath I would use:

//div[@class="div1"]/table[count(tr) = 2]/tr

Is there a jQuery selector expression that will do the same thing?

Here's the HTML snippet:

<div>
  <div class="div1">
    <ul>
      <li>Line 1</li>
    </ul>
    <ul>
      <li>Line 1</li>
      <li>Line 2</li>
    </ul>
  </div>      
</div>

I was hoping this could be done in a single jQuery selector expression (e.g., understood in this Interactive JQuery Tester ). My starting point is:

'div.div1 ul li'

but that also selects the rows from the first table which only has 1 row.

Of course, the "right way" to do this is add IDs or something else to the HTML so that the table can be identified uniquely, however in this instance I have no control over the HTML I am grabbing the data from. The only way I can tell which of the multiple tables to use is from the row count.

Upvotes: 2

Views: 151

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240938

Yes, you can do this with a single jQuery selector.

In your case you could just combine the :has() selector, the :eq() selector, and the :last-child pseudo class in order to select a ul element that has two li children elements. Keep in mind that the :eq() selector accepts an index that is zero-based (which means that we would use an index of 1 in order to select the second li element). The :last-child pseudo class is then used in order to ensure that the second li is in fact the last child element.

$('.div1 ul:has(li:eq(1):last-child)')

Snippet:

$('.div1 ul:has(li:eq(1):last-child)').addClass('selected');
.selected { color: #f00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <div class="div1">
    <ul>
      <li>Line 1</li>
    </ul>
    <ul>
      <li>Line 1</li>
      <li>Line 2</li>
    </ul>
    <ul>
      <li>Line 1</li>
      <li>Line 2</li>
      <li>Line 3</li>
    </ul>
  </div>      
</div>


Alternatively, you could also utilize the :nth-child() pseudo class as well.

$('.div1 ul:has(li:nth-child(2):last-child)')

Snippet:

$('.div1 ul:has(li:nth-child(2):last-child)').addClass('selected');
.selected { color: #f00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <div class="div1">
    <ul>
      <li>Line 1</li>
    </ul>
    <ul>
      <li>Line 1</li>
      <li>Line 2</li>
    </ul>
    <ul>
      <li>Line 1</li>
      <li>Line 2</li>
      <li>Line 3</li>
    </ul>
  </div>      
</div>

Upvotes: 2

Related Questions