Skip to content
Advertisement

how to select $(this) inside a template literal js expression?

I know that every time I call “this” inside the function it will select whatever selector have given it in arguments but how could use template literal like this and get the index of the row generated in the append method ?

$(document).on('click', '.add-row', function () {
  $(this).closest("table").find("tbody").append(`
     <tr>
       <td> ${ $(this).closest("tr").index() } </td>
    </tr>
  `)
});
<html>
  <head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" integrity="sha384-skAcpIdS7UcVUC05LJ9Dxay8AXcDYfBJqt1CJ85S/CFujBsIzCIv+l9liuYLaMQ/" crossorigin="anonymous"></script>
  </head>
  <body>
<table class="table table-bordered">
  <thead>
    <th>INDEX</th>
    <th>SOMETHING</th>
    <th><button class="btn btn-primary add-row">ADD ROW</button></th>
  </thead>
  <tbody></tbody>
</table>
  </body>
</html>

Advertisement

Answer

You’ll need to find the tbody, and see the number of children of that element to get a counter:

$(document).on('click', '.add-row', function () {
  var $tbody = $(this).closest("table").find("tbody");
  $tbody.append(`
     <tr>
       <td> ${ $tbody.children().length } </td>
    </tr>
  `)
});
<html>
  <head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" integrity="sha384-skAcpIdS7UcVUC05LJ9Dxay8AXcDYfBJqt1CJ85S/CFujBsIzCIv+l9liuYLaMQ/" crossorigin="anonymous"></script>
  </head>
  <body>
<table class="table table-bordered">
  <thead>
    <th>INDEX</th>
    <th>SOMETHING</th>
    <th><button class="btn btn-primary add-row">ADD ROW</button></th>
  </thead>
  <tbody></tbody>
</table>
  </body>
</html>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement