Highlighting and Un-Highlight a table row on click from row to row

html, javascript

Solution

I've created a working example of the following on JSFiddle

Javascript:

function toggleClass(el, className) {
    if (el.className.indexOf(className) >= 0) {
        el.className = el.className.replace(className,"");
    }
    else {
        el.className  += className;
    }
}

HTML:

<table class="gridview">
   <tr onclick="toggleClass(this,'selected');"><td></td><td></td></tr>
   <tr onclick="toggleClass(this,'selected');"><td></td><td></td></tr>
   <tr onclick="toggleClass(this,'selected');"><td></td><td></td></tr>
</table>

CSS:

.gridview .selected, .gridview tbody .selected {
    background-color: #6ccbfb;
    color: #fff;
}

Problem

I've been at this problem for awhile with no luck. Please note. No jquery =/ The JS code I have is as following ``` function highlight(){ var table = document.getElementById('dataTable'); for (var i=0;i < table.rows.length;i++){ table.rows[i].onclick= function () { if(!this.hilite){ this.origColor=this.style.backgroundColor; this.style.backgroundColor='#BCD4EC'; this.hilite = true; } else{ this.style.backgroundColor=this.origColor; this.hilite = false; } } } } ``` The HTML is as following ``` <table id="dataTable"> <tr onclick="highlight()"><td>Data1</td><td>Data2</td></tr> <tr onclick="highlight()"><td>Data1</td><td>Data2</td></tr> <tr onclick="highlight()"><td>Data1</td><td>Data2</td></tr> </table> ``` Currently when I click it changes color, however when I click on the second row the first row still remains highlighted. Could you please assist me in accomplishing this task with no jquery? Thank you.

Original source