2

I need to select all the list items in all unordered lists where the count is greater than seven.

This code:

$("ul.seven > li:gt(6)").hide()

is too greedy and works correctly for the first unordered list on the page but hides all subsequent list items of subsequent unordered lists. What is the correct selector?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
maletor
  • 7,072
  • 7
  • 42
  • 63
  • 1
    If you prefer "the correct selector" over a block of callback code which consists of selector *fragments*, see my answer. – BoltClock Oct 25 '12 at 18:21

2 Answers2

2

Try this

$("ul.seven").each(function() {
    $(this).find("> li:gt(6)").hide();
});

or ( which is essentially the same )

$("ul.seven").each(function() {
    $(this).children("li:gt(6)").hide();
});
Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134
1

:gt() collates the entire set of ul.seven > li and picks everything after the sixth li in that combined set, regardless of its parent. It's equivalent to selecting all of those li elements and then performing a .slice() on the result set:

$("ul.seven > li").slice(7).hide();

Which does something very different from what you expect.

You want :nth-child() instead, which behaves more like what you expect of a CSS simple selector:

$("ul.seven > li:nth-child(n+8)").hide();

:nth-child(n+8) means "starting from the 8th child based on a 1-index", which is roughly equivalent to :gt(6) which means "starting from the 7th match based on a 0-index" (confusing, I know). Compare the Selectors spec for :nth-child(), the jQuery API documentation for :gt() and the jQuery API documentation for .slice().

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356