Return N elements from a list in jQuery

Asked

Viewed 300 times

4

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

$('#minha_tabela tr');

There is a selector, method or overload in jQuery that I can return more than one line by passing multiple indexes?

Something like,

$('#minha_tabela tr').get(0, 2, 7);
  • Well, Slice is sequential, you’re saying an arbitrary list right? I’ll see if we have something more specific.

  • Hmm, yes. The index list could be arbitrary. But this I can easily bypass by giving a sort before applying in the method slice. But I’d appreciate it if you’d post something arbitrary :)

2 answers

7


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

Take 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>

<table id="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 a .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>

<table id="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>

1

You can use multiple separator selectors with comma and use the 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)');
  • Renato, the indexes of the array are dynamic (ok, I have a fault for not explaining in the question). Although, I can use something like '[..]nth:child('+i+')[..]'.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.