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
  • 4,240
  • 5
  • 33
  • 50

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
  • 58,591
  • 15
  • 114
  • 126
  • 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
  • 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
  • CSS is not a programming language. I think that's impossible. You can make weird tricks, but not bulletproof. – Marcos Pérez Gude Apr 29 '16 at 10:06