Question

I've got some tables. They all have the same class, they're all generated by the same code. I'd like to only show three rows of each table by hiding the rest of the rows using jQuery. Later on I'll add a link to allow the user to expand a given table, but for now I'd like to just hide the later elements.

I'm doing this with slice(), but I notice that slice() does not reset its index when it moves on to the next table. I'm probably doing something wrong in my jQuery selector.

Here's the JSFiddle, I'll include the HTML and JS on this post anyway just in case. http://jsfiddle.net/3pf3z/1/

JS

$( document ).ready(function() {
    $( ".booking tr" ).slice(3).hide();
});

HTML

<table class="booking">
    <tr><td>1</td></tr>
    <tr><td>2</td></tr>
    <tr><td>3</td></tr>
    <tr><td>4</td></tr>
</table>

<br /><br />

<table class="booking">
    <tr><td>1</td></tr>
    <tr><td>2</td></tr>
    <tr><td>3</td></tr>
    <tr><td>4</td></tr>
    <tr><td>5</td></tr>
    <tr><td>6</td></tr>
</table>
Was it helpful?

Solution 2

One solution is to use each():

$( document ).ready(function() {
    $( ".booking" ).each(function() {
       $(this).find("tr").slice(3).hide();
    });
});

Demo at: http://jsfiddle.net/efWpN/1/

jQuery docs on each()

OTHER TIPS

Try

$(".booking").each(function(){
    $(this).find('tr:lt(3)').hide();   
});

http://jsfiddle.net/3pf3z/2/

$( document ).ready(function() {
$( ".booking" ).each(function(){
    $(this).find("tr").slice(3).hide();
});
});

http://jsfiddle.net/3pf3z/3/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top