Jump to content

function on each element of an array


Recommended Posts

Can somebody explain me, why is necessary to write:

childTD[i].addEventListener("click", function(){changeColor(this);});

and not just:

childTD[i].addEventListener("click", changeColor(this));

Here is the whole code:

var ParentTable = document.getElementById("mytable");var childTD = ParentTable.getElementsByTagName("td");for(i=0;i<childTD.length;i++) {	childTD[i].addEventListener("click", function(){changeColor(this);});}function changeColor(element) {	element.style.backgroundColor="red";}

Thanks a lot!

Link to comment
Share on other sites

What value does "this" have in that context?


You probably should just use the event object that's passed to the function instead:

childTD[i].addEventListener("click", changeColor);
function changeColor(e) {  var element = e.target;  element.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...