Using DOM to get item id inside onclick

I am trying to access the id of the elements retrieved with getElementsByTagName , but I am getting an error:

 var divs=document.getElementsByTagName("div"); for(var i=0;i<divs.length;i++){ divs[i].onclick=function(){ alert(divs[i].id); } } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> </head> <body> <div id="1">1</div> <div id="2">2</div> <div id="3">3</div> <div id="4">4</div> <div id="5">5</div> <div id="6">6</div> </body> </html> 

Error:

Uncaught TypeError: Unable to read property 'id' from undefined

When i change

 alert(divs[i].id); 

to

 alert(this.id); 

It works, but I don’t understand why this is happening.

+5
source share
1 answer

 var divs=document.getElementsByTagName("div"); for(var i=0; i < divs.length;i++){ divs[i].onclick=function(){ alert(this.id); } } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> </head> <body> <div id="1">1</div> <div id="2">2</div> <div id="3">3</div> <div id="4">4</div> <div id="5">5</div> <div id="6">6</div> </body> </html> 

this.id works because:

After adding the onclick element to the element, the element calls the function if you click on the element.

After the loop, i will be increased to the length of the divs array (which is 6). And when the element is clicked and the function is called, divs[6] is undefined, and you cannot get the identifier undefined, while the function can understand this points to the element with a click, and it will work.

+2
source

All Articles