put variable in jquery selector

0

I looked at other similar questions, but their answers did not help me because the selector I'm using is different.

I want to get a tr in a tbody of a table , using the nth-child(n) selector but in n I want to put a variable and do something like this:

$("tbody").find("tr:nth-child(' + posicao + ')").addClass("classe");

This way it's not working, and neither have I tried and seen the answers here.

    
asked by anonymous 03.01.2017 / 19:47

1 answer

4

You are doing concatenation badly, you should use "" or "", but then you were using the two, ie the peliculas (") were considered part of the selector:

posicao = 2;
$("tbody").find('tr:nth-child(' + posicao + ')').addClass("classe");
.classe {
 background-color: red; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John</td>
        <td>Doe</td>
        <td>[email protected]</td>
      </tr>
      <tr>
        <td>Mary</td>
        <td>Moe</td>
        <td>[email protected]</td>
      </tr>
      <tr>
        <td>July</td>
        <td>Dooley</td>
        <td>[email protected]</td>
      </tr>
    </tbody>
  </table>
    
03.01.2017 / 19:51