jQuery selector help needed

Hi to all,

I am trying to select the nth row of a summary section that has 4 calculations: Totals, Avg, Min and Max.

When I select the last one, it works as expected, using this console command:
$$('.kn-table-totals:last-of-type')

When I hover over the found result, I can see the blue highlight in the view at left, like this:

Result:

But if I try to select the Avg row which is the second one, it finds nothing.

This is my selector command that fails:

$$('.kn-table-totals:nth-of-type(2)')

Result:

What am I doing wrong?

BTW, I know how to select any summary row using the :contains pseudo-selector, but I really want to understand the nth-of-type.

Normand

For reliability reasons, I would recommend against using :nth-* or :contains for this purpose. Instead, I would select .kn-table-totals and then use normal array operations like .find() or .filter() to find the value you’re looking to target.

Nevertheless, here’s why your selector isn’t working: :nth-* selectors do not count instances of a selector in the document. Instead, they select nth instances among a list of siblings, that also happen to match the selector.

So, say you have this list of elements:

<ul>
  <li>Test 1</li>
  <li class="highlight">Test 1</li>
  <li>Test 1</li>
  <li class="highlight">Test 1</li>
</ul>

If you want to select the second instance of .highlight, you might try .highlight:nth-child(2). But that’ll actually select the first instance of .highlight because it is the second among its siblings. For this reason,.highlight:nth-child(4) will actually select the second instance of .highlight. Meanwhile, :nth-of-type behaves just like :nth-child with the added stipulation of selecting among siblings of the same type.

Thankfully, with the introduction of CSS Level 4, we now get of S notation! It is already supported by all major browsers, so it should be pretty safe to use. Now, to select the second instance of .highlight in the example above, we can use :nth-child(2 of .highlight) :tada: .

3 Likes

Wow, I wish I understood any of that :+1::wink:

Great! That new selector nth-child n of S works beautifully.

This is what I tested:

$$('.kn-table-totals:nth-child(2 of .kn-table-totals) td:nth-child(8)')[0].textContent

And I get $94.34 as expected.

Now I understand how all this works.

Thanks David,
Norm