0

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);
      }
   }

 })

});
1
  • 3
    I think it should be for(var i=0;i<hmore.length;i++){ rather than for(var i=1;i<=hmore.length;i++){ Commented Aug 11, 2016 at 12:27

1 Answer 1

2
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 <=

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

Comments

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.