Reputation: 53
I have a table which contains unordered lists with dozens of list items in each list. The lists share the same class. I want to loop through each list and if it has more than 5 list items I want to show the top 5 and hide the rest and display a link to another page.
I am having trouble with the logic as I am only able to do what I stated above with the first unordered list and am subsequently hiding every other list that follows. How do check each list and break if there aren't more than 5 rows and continue to the next one?
Below is the basic HTML and JS that I've tried.
Thanks in advance for your help!
$('ul.resultsList').each(function () {
if($(this).children().length > 4) {
$('li:gt(4)').hide();
$('.seeMore').show();
}else {
$('.seeMore').hide();
return false;
}
});
<table id="docResults">
<thead>
<tr>
<th>Names</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<ul class="resultsList">
<li>Smith, J</li>
<li>Smith, F</li>
<li>Smith, K</li>
<li>Smith, L</li>
<li>Smith, M</li>
<li>Smith, N</li>
<li>Smith, O</li>
<li>Smith, P</li>
<li>Smith, Q</li>
<li>Smith, R</li>
</ul>
<a href="#" class="seeMore">
</td>
</tr>
<tr>
<td>
<ul class="resultsList">
<li>Smith, J</li>
<li>Smith, F</li>
<li>Smith, K</li>
<li>Smith, L</li>
<li>Smith, M</li>
<li>Smith, N</li>
<li>Smith, O</li>
<li>Smith, P</li>
<li>Smith, Q</li>
<li>Smith, R</li>
</ul>
<a href="#" class="seeMore">
</td>
</tr>
</tbody>
</table>
Upvotes: 0
Views: 246
Reputation: 67207
Try to use $(this)
object at this context for invoking .hide()
$('ul.resultsList').each(function () {
var td = $(this).closest("td");
if($(this).children().length > 4) {
$('li:gt(4)', this).hide();
$('.seeMore', td).show();
}else {
$('.seeMore', td).hide();
}
});
Upvotes: 1