There is a document in which there is a table:

<table> <tr> <th>county</th> <th>city</th> <td><div class="rem">delete</div></td> </tr> <tr> <td>russia</td> <td>moscow</td> <td><div class="rem">delete</div></td> </tr> <tr> <td>usa</td> <td>washington</td> <td><div class="rem">delete</div></td> </tr> <tr> <td>australia</td> <td>sidney</td> <td><div class="rem">delete</div></td> </tr> </table> 

There is code that works when placed in the console, but when added to .html or loadable .js, it refuses to work, jQuery is connected, everything else works, but this piece does not, although it checked the logic through the console. everything works fine, here's the code:

 $(document).ready(function(){ $('.rem').each(function(){ $(this).click(function(){ alert($(this).parents('td').siblings('td:first').text()); }); }); }); 

alert should display the name of the country .. Help me figure it out, thanks)

    2 answers 2

    It is necessary to write like this:

     $(function(){ $('table').on('click', '.rem', function(){ alert($(this).closest('tr').find('td:first').text()); }); }); 

      Like this:

       <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <table> <tr> <th>county</th> <th>city</th> <th class="rem">action</th> </tr> <tr> <td>russia</td> <td>moscow</td> <td class="rem">delete</td> </tr> <tr> <td>usa</td> <td>washington</td> <td class="rem">delete</td> </tr> <tr> <td>australia</td> <td>sidney</td> <td class="rem">delete</td> </tr> </table> <script type="text/javascript"> $(document).ready(function(){ $('.rem').each(function(){ $(this).click(function(){ alert($(this).siblings('td:first').text()); }); }); }); </script> 
      • doesn't work either - pirogi
      • @pirogi Added full script text. Everything works. If you don't, then the problem is something else. - Dmitriy
      • corrected the html there in the last td div it lies with the class rem, but my code does not work anyway - pirogi
      • @pirogi If there is only one element in a cell, you can set a class for it and use my function to click on it. Otherwise, I can’t help you until morning. Already not at the computer. - Dmitriy
      • of element 2, I didn’t write a second one, but you see, I open my page, it doesn’t work, I open the console, I write it there and it starts working right away ... I don’t understand it - pirogi