5

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.

4
  • 4
    Within the click handler, this refers to the element clicked, and it no longer has a reference to the appropriate i Commented Aug 7, 2015 at 1:39
  • 2
    If you must use alert(divs[i].id);, try for (var i = 0; i < divs.length; i++) { (function(i) { divs[i].onclick = function () { alert(divs[i].id); } })(i); }. Commented Aug 7, 2015 at 2:07
  • @akinuri I get a new way to solve the problem , thank you! Commented Aug 7, 2015 at 2:23
  • @Jrd I get it ,thank you! Commented Aug 7, 2015 at 2:24

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

thank you for your help ^_^ I add alert(i); before alert(divs[i].id); and test, it alerts 6, then I have a new qusetion : why I click <div id="1">1</div>the i=6 instead of 1?
@nian I tried to make it clear in my answer. i will be increased to the length of divs array, which is 6, after the loop / adding all onclick events on 6 divs. So when you click on one of these elements, which is after the loop, i = 6 whichever element you clicked.
Sorry, my English may be poor and I wish I made myself understood.
I get it ! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.