AB Siddik AB Siddik - 14 days ago 5
Javascript Question

Why show this error Uncaught TypeError: Cannot read property 'addEventListener' of undefined

I have some JavaScript code that gives this error

Uncaught TypeError: Cannot read property 'addEventListener' of undefined


My code:

HTML:

<div class="main">
<h1 id="our-heading">The page heading</h1>
<button id="button">Add Item</button>
<ul id="our-list">
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
<li>Item four</li>
<li>Item five</li>
</ul>
</div>


Javascript:

var ourHeadline = document.getElementById("our-heading");
var listItems = document.getElementById("our-list").getElementsByTagName("li");

for (var i = 0; i<= listItems.length; i++){
listItems[i].addEventListener("click", activateItem );
}

function activateItem(){
ourHeadline.innerHTML = this.innerHTML;
}


Please anyone give me the solution

Answer

loop till the last item of array only, in your current code you are looping till the length of the array listItems

for (var i = 0; i<= listItems.length; i++){
    listItems[i].addEventListener("click", activateItem );
}

Since array index start for 0 , for the last iteration of the loop you will get the above mentioned undefined error due to the below code

listItems[i].addEventListener

change your code to

for (var i = 0; i< listItems.length; i++){
    listItems[i].addEventListener("click", activateItem );
}
Comments