Reputation: 31663
I have html list, which contains visible and hidden elements. The visibility changes dynamically over time (some elements become hidden, some are shown).
<ul>
<li> </li>
<li style="display:none"> </li>
<li> </li>
<li style="display:none"> </li>
<li> </li>
<li> </li>
<li> </li>
</ul>
What I want is the list to display at most X elements, so <li>
s beyond X should be hidden. What is the suggested way of achiving that? I've come up with two ideas:
<ul>
and add overflow: hidden
(overhead <li>
's won't be visible). It's simple but will work only when <li>
's have constant size and you can predict number of elements that will fit into the list.Can you suggest preferred approach or answer if there is a way to do that in pure CSS?
Upvotes: 0
Views: 294
Reputation: 2407
Using nth child selector you can achive it with pure css. But be aware that IE does not support it.
In this example instead of applying display:none, I applied a color:#ff0000 so you can appreciate the result. Replace the 4 for the number of LI elements needed to be displayed.
<style>
ul li:nth-child(1n+4)
{
color:#ff0000;
}
</style>
<ul>
<li> a </li>
<li> b </li>
<li> c </li>
<li> d</li>
<li> e </li>
<li> f </li>
<li> g </li>
</ul>
Upvotes: 1
Reputation: 410
You can make a function which controlls hiding of visible elements
function checkList()
{
$('ul li:visible:gt(X)').hide();
}
and you need to call the function on every change to UL and it's LIs. I would suggest some more identification to UL, perhaps via ID attribute.
Upvotes: 1
Reputation: 16198
Use the gt()
selector, along with :visible
$('li:visible:gt(20)').hide()
Alternatively, use slice()
:
$('li:visible').slice(20).hide()
Upvotes: 2