What does this jQuery snippet do?
This jQuery code applies conditional formatting to rows in an HTML table with the class .demo-table. Here's how it works:
- It waits for the DOM to be ready using
$(function() {...})
. - It loops through each
<td>
(table cell) in.demo-table
. - For each cell:
- It checks the cell's text content.
- If the text is a number greater than or equal to 5.5, it sets the entire row’s background color (
<tr>
) to#ecc87a
(light yellow). - If the number is less than 5.5, it sets the row’s background color to
#dcccaa
(light beige).
JS
$(function() {
$('.demo-table td').each(function() {
if ($(this).text() >= 5.5) // if grade is 5.5 or higher
$(this).parent().css('backgroundColor', '#ecc87a');
else
$(this).parent().css('backgroundColor', '#dcccaa');
});
});
HTML
<div class="demo-container">
<table class="demo-table" width="100%" cellpadding="0" cellspacing="1">
<tr>
<th>Student's Name</th>
<th>Grade</th>
</tr>
<tr>
<td>Brown, Emma</td>
<td>4.0</td>
</tr>
<tr>
<td>Johnson, Olivia</td>
<td>2.6</td>
</tr>
<tr>
<td>Smith, Liam</td>
<td>4.5</td>
</tr>
<tr>
<td>Williams, Isabella</td>
<td>5.5</td>
</tr>
</table>
</div>
CSS
.demo-container table {
border-collapse: separate;
border-spacing: 1px;
}
.demo-container .demo-table td {
padding: 4px 8px;
}
.demo-container .demo-table th {
padding: 2px 4px;
background-color: #454545;
color: #fff;
text-align: left;
}
.demo-container {
margin-bottom: 2em;
}
.demo-container th,
.demo-container td {
color: #fff;
padding: 0.25em 0.5em;
text-align: left;
}
.demo-container th {
background: #3d4c53;
}
.demo-container tr:first-child th:first-child {
border-top-left-radius: 6px;
}
.demo-container tr:first-child th:last-child {
border-top-right-radius: 6px;
}
.demo-container tr:last-child td:first-child {
border-bottom-left-radius: 6px;
}
.demo-container tr:last-child td:last-child {
border-bottom-right-radius: 6px;
}
Alternate table row styles
Conditional formatting of table rows
Copy text to clipboard
Disable space input in text fields
Multi step form with progress indicator
Read more or less
Remove the leading and trailing space
Short functions
Toggle visibility with a slide effect
Toggle visibility without pushing content down
Validate checkboxes
Validate input fields
Validate radio buttons
Validate TinyMce editor