How to change the selected table row color using inline Javascript in HTML I am trying in this way
onclick="this.style.backgroundColor='blue'" I am writing this in
<tr onclick="this.style.backgroundColor='blue'"> <td>row1</td> <td>row2</td> </tr>
When I click on row1 that row color should change to blue.When I again click on row2 then row1 background color reset to normal and row2 background color become blue How can I achieve this.
If you really need a single lined js, then (for modern browsers):
.selected { background-color: coral; } table { border-spacing:0; }
<table> <tr onclick="var s = this.parentNode.querySelector('tr.selected'); s && s.classList.remove('selected'); this.classList.add('selected');"> <td>row1</td> <td>row2</td> </tr> <tr onclick="var s = this.parentNode.querySelector('tr.selected'); s && s.classList.remove('selected'); this.classList.add('selected');"> <td>row1</td> <td>row2</td> </tr> </table>
You can not do it using inline javascript.
I would use something like this ( for modern browsers )
// delegate the event handling to the table document.querySelector('table').addEventListener('click', function(e) { var closestCell = e.target.closest('td'), // identify the closest td when the click occured activeCell = e.currentTarget.querySelector('td.selected'); // identify the already selected td closestCell.classList.add('selected'); // add the "selected" class to the clicked td if (activeCell) activeCell.classList.remove('selected'); // remove the "selected" class from the previously selected td })
.selected { background: blue; color: white; }
<table> <tr> <td>row1</td> <td>row2</td> </tr> </table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.