1
var task = [document.getElementById('*'),
            document.getElementById('+')];

var i;      
var displayfield  = document.getElementById('displayarea');

displayfield.disabled=true;


for(i=0;i<task.length;i++){

    task[i].onclick = function(){

        console.log('entered?');

        displayfield.innerHTML = task[i].id;

        console.log('clicked');

        console.log(task[i].id.length);
    }
}

i am getting this error "Cannot read property 'id' of undefined".. but when i type task[0] or task[1] in my browser console and give correct result like "*" and "+"....

Barmar
  • 741,623
  • 53
  • 500
  • 612
Prime
  • 15
  • 2

1 Answers1

0

That's a classical mistake.

You have defined i as a global var, so after your for loop the value of i will be = 2.

When you click the element it will always call task[2] which is undefined.

To do what you want to do, you can call this inside the functon

task[i].onclick = function(){
  console.log(this.id);
}