Return N elements from a list in jQuery

4

I have a list of elements, say a list of rows in a table:

$('#minha_tabela tr');

Is there a selector, method or overload in jQuery so I can return more than one line passing multiple indexes?

Something like,

$('#minha_tabela tr').get(0, 2, 7);
    
asked by anonymous 21.11.2014 / 05:21

2 answers

7

If you want a continuous list, it can be slice :

See an example:

$('#tabela tr').slice( 2, 4 ).css( "background-color", "red" );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><tableid="tabela">
  <tr><td>Linha 1</td><td>0001</td></tr>
  <tr><td>Linha 2</td><td>0002</td></tr>
  <tr><td>Linha 3</td><td>0003</td></tr>
  <tr><td>Linha 4</td><td>0004</td></tr>
  <tr><td>Linha 5</td><td>0005</td></tr>
</table>


But if you want values with a varied sequence, you can use .filter() combined with .inArray() :

$('#tabela tr').filter( function( index ) {
   return $.inArray(index, [0,2,7]) >= 0;
} ).css( "background-color", "red" );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><tableid="tabela">
  <tr><td>Linha  1</td><td>0001</td></tr>
  <tr><td>Linha  2</td><td>0002</td></tr>
  <tr><td>Linha  3</td><td>0003</td></tr>
  <tr><td>Linha  4</td><td>0004</td></tr>
  <tr><td>Linha  5</td><td>0005</td></tr>
  <tr><td>Linha  6</td><td>0006</td></tr>
  <tr><td>Linha  7</td><td>0007</td></tr>
  <tr><td>Linha  8</td><td>0008</td></tr>
  <tr><td>Linha  9</td><td>0009</td></tr>
  <tr><td>Linha 10</td><td>0010</td></tr>
</table>
    
21.11.2014 / 05:44
1

You can use multiple selectors by separating with a comma and using nth-child to pick up a specific element. In the case of your example, it would look like this:

// no nth-child, indices começam no um, não no zero
$('#minha_tabela tr:nth-child(1), #minha_tabela tr:nth-child(3), #minha_tabela tr:nth-child(8)');
    
21.11.2014 / 05:40