简体   繁体   中英

Javascript Uncaught TypeError: Cannot set property of undefined

I have a problem with my code in JavaScript, probably some stupid mistake but I can't find it... an error occurs.

Uncaught TypeError: Cannot set property 'innerHTML' of undefined

Even though the code seems to do what it should (creates tasks which have a header of Task 1 , Task 2 , Task 3 and so on).. How can I fix that? Maybe there is a shorter way to give my tasks numbered headers?

document.addEventListener("DOMContentLoaded", function(){

  var add=document.querySelector("#addTaskButton");
  var tasklist=document.querySelector("#taskList");
  var clickcount=0;

  add.addEventListener("click",function(event){
   var newTask=document.createElement("li");
   tasklist.appendChild(newTask);
   var newh1=document.createElement("h1");
   newTask.appendChild(newh1);

  clickcount+=1;
   if(clickcount==1){
     var h1=document.querySelector("h1");
     h1.innerText="Task 1";
   }else if(clickcount>1){
     var hmore=document.getElementsByTagName("h1");
     for(var i=1;i<=hmore.length;i++){
       hmore[i].innerHTML="Task "+(i+1);
      }
   }

 })

});
 for(var i=1;i<=hmore.length;i++){ 

Array-like objects in JavaScript are zero indexed.

The length is the number of items in the object.

This means that if you have an array with 3 items in it, they exist at indexes 0, 1, and 2.

So when i == hmore.length you have gone one beyond the end .

You need to test for < not <=

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