简体   繁体   中英

Using DOM to get element id's inside onclick

I'm trying to access id's of elements fetched by getElementsByTagName but I'm 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> 

The error is:

Uncaught TypeError: Cannot read property 'id' of undefined

When I change

alert(divs[i].id); 

to

alert(this.id); 

it works, but I don't understand why this happens.

 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 you added a onclick to the element, the element call 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 can't get id of undefined, while the function can understand this points to the clicked element and it will work.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM