0

I have a table that highlight the tr (row) on click, and I can highlight multi rows on every click but I want to have only one row to be highlight in table. how to remove the highlight class from sibling rows. code below

JavScript

        document.querySelector("table").addEventListener("click", function (e) {
            // Is it a click on a tr in this table?
            var tr = e.target.closest("tr");
            if (tr && this.contains(tr)) {
                // Yes, toggle highlight
                tr.classList.toggle("highlight");
            }
        });

css

  .highlight {
        background-color: #ffeaea;
    }
vanje
  • 10,180
  • 2
  • 31
  • 47
Mohammad I
  • 78
  • 5
  • 1
    [JavaScript is not Java](https://stackoverflow.com/questions/2018731/why-is-javascript-called-javascript-since-it-has-nothing-to-do-with-java) – Koenigsberg Aug 22 '22 at 07:50
  • Either loop through all other table rows, and explicitly remove the class from those (or loop over _all_ rows and remove it, but the you will have to _add_ it to the current row afterwards, instead of _toggling_ it on that one) - or _remember_ the last clicked row in a variable, so that you can toggle the class off specifically for that one again first. – CBroe Aug 22 '22 at 10:01

2 Answers2

1

If you don't mind I used @CBroe's suggestion here, to remember the previously selected TR:

let prevTr = undefined

document.querySelector("table").addEventListener("click", function (e) {
    let tr = e.target.closest("tr");
    if (tr && this.contains(tr)) {
        if(prevTr) prevTr.classList.remove("highlight")
        tr.classList.add("highlight");
        prevTr = tr
    }
});
Kokodoko
  • 26,167
  • 33
  • 120
  • 197
0

I ended up adding below code and issue resolved.

 $('.table tr').removeClass("highlight");
Mohammad I
  • 78
  • 5