put variable in jquery selector

Asked

Viewed 330 times

0

I researched other similar questions, but their answers didn’t help me because, the selector I’m using is different.

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

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

this way is not working, and nor of others that I tried and saw in the answers here.

  • 1

    Try using the jQuery function specific to this, the .eq(n); - Would look like this $("tbody").find("tr").eq(suaVariavel).addClass("foo");

  • @dsantoro and the response? :)

  • It was just a suggestion not worth as an answer rs.

1 answer

4


You are wrong to concatenate, you must use "" or '', but then you were using both, ie the pelicas (' ) 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>

Browser other questions tagged

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