Jump to content

change color of each <td> onClick event


Recommended Posts

hello, I want to develop a script which could change the each and every <td> cell in a table when clicking.What i am considering to achieve this is by assigning each <td> an id and use it as a function parameter, so that in function i could change the color of that particular cell. Something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Untitled Document</title><script type="text/javascript">function changeColor(id){var cell = document.getElementById(id);cell.style.background = red;//cell.style.color = black;}</script></head> <body><table><tr><td id='cell' onclick="changeColor('cell')">a1</td></tr></table></body></html>

but since onclick would not work for the <td> so what else better way to perform this. If someone could suggest better alternative for achieving sucha a thing it would be very kind. Note: All this to start my online movie ticket booking self learning project, so please guide me to the appropriate directionThanks in advance

Link to comment
Share on other sites

1) you do not require id ref for each cell using 'this' refers to current element that click event was triggered on <tr><td onclick="changeColor(this)">a1</td></tr>2) now that you are refering to current element

function changeColor(elem)

3) when refering to background color you use style.backgroundColor=4) colour is define within quotes as in 'red', "red" or using hex '#FF0000', "#FF0000"

elem.style.backgroundColor = "red";

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...