Tengo una tabla Bootstrap 5 con la tabla de clase rayada. Cuando el uso hace clic en una fila, tengo un código jQuery que alterna la clase text-success en la fila para resaltarla/no resaltarla.
El resaltado funciona correctamente en las filas que no tienen el fondo rayado, pero no tiene efecto en las filas que sí lo tienen.
Esta técnica funcionó correctamente en cualquier fila de la tabla cuando estaba usando Bootstrap 3.7
Aquí hay un código de ejemplo.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no"> <title>Test</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.12.0/css/all.css"> </head> <body> <main class="container clearfix"> <div class="row mt-4 mb-4"> <div class="col-md-8 offset-md-2"> <table id="mytable" class="table table-striped table-sm"> <thead> <tr> <th>Col1</th> <th>Col2</th> </tr> </thead> <tbody> <tr> <td>Column 1</td> <td>Column 2</td> </tr> <tr> <td>Column 1</td> <td>Column 2</td> </tr> <tr> <td>Column 1</td> <td>Column 2</td> </tr> </tbody> </table> </div> </div> </main> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script> <script> $("#mytable tbody tr").click(function () { $(this).toggleClass("text-success") }) </script> </body> </html>Eso es porque en bootstrap 5 existe esta regla:
.table-striped > tbody > tr:nth-of-type(2n+1) > * { --bs-table-accent-bg: var(--bs-table-striped-bg); color: var(--bs-table-striped-color); }Este selector anterior anula en términos de especificidad su selector, por lo que solo necesita hacer su más específico
//$("#mytable tbody tr > *").click(function() { // $(this).toggleClass("text-success") //}) //arrow function version //$("#mytable tbody tr > *").click(e => $(e.currentTarget).toggleClass("text-success")) //updated version - OP Comment - "Great, thanks. Is there a way to highlight the whole table row instead of just the column I click one?." $("#mytable tbody tr > *").click(e => $(e.currentTarget).parent().find('td').toggleClass("text-success")) <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <main class="container clearfix"> <div class="row mt-4 mb-4"> <div class="col-md-8 offset-md-2"> <table id="mytable" class="table table-striped table-sm"> <thead> <tr> <th>Col1</th> <th>Col2</th> </tr> </thead> <tbody> <tr> <td>Column 1</td> <td>Column 2</td> </tr> <tr> <td>Column 1</td> <td>Column 2</td> </tr> <tr> <td>Column 1</td> <td>Column 2</td> </tr> </tbody> </table> </div> </div> </main>