3

How can I count children <li> within a <ul>?

I want to hide last <li> if <ul> is have less than or equals to 6 <li>'s in one <ul>.

CODE

<ul>
  <li>one</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
  <li class="more"><span>Hide this if only 6 li's are there in this ul</span></li>
</ul>

Fiddle

richa_pandey
  • 4,210
  • 3
  • 31
  • 48

3 Answers3

4

you can use the nth-of-type()(or nth-child()) plus adjacent selector +

li {
  background: red
}
.more {
  background: green
}
li:nth-of-type(5) + li {
  display: none
}
<h1> 6 items </h1>

<ul>
  <li>one</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
  <li class="more"><span>Hide this if only 6 li's are there in this ul</span>
  </li>
</ul>

<h1> 5 items </h1>


<ul>
  <li>one</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li class="more"><span>Hide this if only 6 li's are there in this ul</span>
  </li>
</ul>

<h1> 7 items </h1>

<ul>
  <li>one</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
  <li class="more"><span>Hide this if only 6 li's are there in this ul</span>
  </li>
  <li>Seven</li>
</ul>
dippas
  • 52,735
  • 15
  • 110
  • 120
  • this actually solves whatever i have written in my query but one more condition is... i need to hide it if `
  • ` count is less than or equal to 6.
  • – richa_pandey Apr 29 '16 at 09:58
  • that's different than your Original question. – dippas Apr 29 '16 at 09:59
  • No, it's exactly her original question. I put a comment at start instead of this kind of answers because I understand perfectly that she needs to count 6 elements – Marcos Pérez Gude Apr 29 '16 at 10:01
  • @MarcosPérezGude ya exactly 6, but not less than 6. why downvote? – dippas Apr 29 '16 at 10:02
  • 1
    @Marcos Pérez Gude: Her original question says "only 6", and now she's saying "one more condition is... i need to hide it if
  • count is less than or equal to 6."
  • – BoltClock Apr 29 '16 at 10:02