I have a data table with a dropdown box that sorts the table by column. I am trying to highlight the column that is selected/sorted by the dropdown. I am using the following code to obtain the index of the dropdown item:
<script>
var sel = document.getElementById('asorting').selectedIndex;
alert(sel);
</script>
I am using the following CSS code to highlight the column:
<style>
table td:nth-of-type(3)
{
background-color:#E0E0E0;
}
</style>
Both of these work on their own, but I am trying to update the "table td:nth-of-type(3)" to change based on the value of my sel variable. I have tried using (" + sel + ") to feed the variable to the CSS, but that is not working.
I am not very experienced in JS and have not been able to find anything on this site that relates exactly to what I am trying.
Any help would be greatly appreciated.
You can toggle classes in javascript by arriving at a logic like this
<html>
<head>
<script>
function changeStyle(v){
elements = document.getElementsByClassName('hightlight');
if(elements.length > 0){
for (let element of elements){
element.classList.remove('hightlight');
}
}
document.getElementById('data').children[parseInt(v)-1].className = "hightlight";
}
</script>
</head>
<body>
<style>
.hightlight {
color : red
}
</style>
<select id="asorting" onchange="changeStyle(this.value)">
<option class="row" value="1">one</option>
<option class="row" value="2">two</option>
<option class="row"value="3">three</option>
</select>
<table>
<tbody id="data">
<tr>
<td>one</td>
</tr>
<tr>
<td>two</td>
</tr>
<tr>
<td>three</td>
</tr>
</tbody>
</table>
</body>
</html>