Yes, you can highlight a row in an HTML table based on the content of one of its columns using CSS in combination with JavaScript. CSS alone cannot conditionally style elements based on their content, but you can use JavaScript to add a class to the row if it contains a certain string. Here's how you can do it:
HTML Structure
<table id="myTable">
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
<tr>
<td>John Doe</td>
<td>30</td>
<td>New York</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>25</td>
<td>Los Angeles</td>
</tr>
<tr>
<td>Mike Johnson</td>
<td>40</td>
<td>Chicago</td>
</tr>
</table>
CSS for Highlighting
.highlight {
background-color: yellow; /* Change this to your desired highlight color */
}
JavaScript to Add Highlight Class
You can use the following JavaScript code to check each row and add the highlight class if a certain string is found in any of the columns.
document.addEventListener("DOMContentLoaded", function() {
const table = document.getElementById("myTable");
const searchString = "Jane"; // The string you want to search for
for (let i = 1; i < table.rows.length; i++) { // Start from 1 to skip the header row
const row = table.rows[i];
for (let j = 0; j < row.cells.length; j++) {
if (row.cells[j].innerText.includes(searchString)) {
row.classList.add("highlight");
break; // No need to check other cells in this row
}
}
}
});
Explanation
- HTML: A simple table structure with a header and some rows of data.
- CSS: A class called
highlight that changes the background color of the row.
- JavaScript:
- Waits for the DOM to load.
- Loops through each row of the table (skipping the header).
- Checks each cell in the row for the specified string.
- If the string is found, it adds the
highlight class to that row.
Usage
You can change the searchString variable in the JavaScript code to whatever string you want to search for. When the page loads, any row containing that string will be highlighted.
This approach allows you to dynamically highlight rows based on their content using a combination of HTML, CSS, and JavaScript.