Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Sep 2011
    Thanked 0 Times in 0 Posts

    Unhighlighting the last clicked row in a table


    The below code works great except for the fact that it does not unhighlight the last row that was clicked on. For example, if I were to click on a new row, it would change color which is perfect.

    However, if I were to select another row, the previous selected row does not change back to its default color (white). How can the code below be modified so as to restore the previous clicked row to its original color if a new row has been clicked on?

    <!DOCTYPE html>
    <style type="text/css">
    #mstrTable {
         border: 1px solid black
    #mstrTable td, th {
         border: 1px solid black
    #mstrTable tr.normal td {
        color: black;
        background-color: white;
    #mstrTable tr.highlighted td {
        color: white;
        background-color: gray;
      <table id="mstrTable">
            <th>File Number</th>
    <script type="text/javascript">
    //assumes one thead and one tbody
    var table = document.getElementById("mstrTable");
    var thead = table.getElementsByTagName("thead")[0];
    var tbody = table.getElementsByTagName("tbody")[0];
    tbody.onclick = function (e) {
       e = e || window.event;
       var td = e.target || e.srcElement; //assumes there are no other elements inside the td
       var row = td.parentNode;
       row.className = row.className==="highlighted" ? "" : "highlighted";
    thead.onclick = function (e) {
       e = e || window.event;
       var th = e.target || e.srcElement;  //assumes there are no other elements in the th

  2. #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Sydney, Australia
    Thanked 740 Times in 729 Posts
    You need to add a loop that sets all rows to the default colour before changing the colour of the one that was clicked on.
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  3. Users who have thanked felgall for this post:

    jason_kelly (01-16-2013)

  4. #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Thanked 4,947 Times in 4,908 Posts
    My original code did it all correctly. Why did you stop using it?
    Be yourself. No one else is as qualified.

  5. Users who have thanked Old Pedant for this post:

    jason_kelly (01-16-2013)


Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts