I have a Bootstrap 5 table with the class table-striped. When the use clicks on a row, I have some jquery code that toggles the class text-success on the row to highlight/unhighlight it.
The highlight works correctly on rows that do not have the striped background but has no effect on rows that do have a striped background.
This technique worked correctly on any row in the table when I was using Bootstrap 3.7
Here's some example code. Thanks for any suggestions
<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/[email protected]/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.12.0/css/all.css">
</head>
<body>
<main >
<div >
<div >
<table id="mytable" >
<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/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script>
$("#mytable tbody tr").click(function () {
$(this).toggleClass("text-success")
})
</script>
</body>
</html>
CodePudding user response:
That's because in bootstrap 5 there is this rule:
.table-striped > tbody > tr:nth-of-type(2n 1) > * {
--bs-table-accent-bg: var(--bs-table-striped-bg);
color: var(--bs-table-striped-color);
}
This selector above overrides in terms of specificity your selector, so you just need to make your more specific
//$("#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/[email protected]/dist/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<main >
<div >
<div >
<table id="mytable" >
<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>