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;
    }
2
  • 1
    JavaScript is not Java Commented Aug 22, 2022 at 7: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. Commented Aug 22, 2022 at 10:01

2 Answers 2

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
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

I ended up adding below code and issue resolved.

 $('.table tr').removeClass("highlight");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.