educative.io

Educative

What is the Error 2?

pls kindly explain the error i get using my code vs the provided solution

MINE:
var addButton = document.getElementById(‘addTodo’);
var unorderedlist = document.getElementById(‘todolist’);

addButton.onclick = function() {
var listItem = document.createElement(‘li’);
listItem.innerHTML = document.getElementById(‘todo’).value;
listItem.appendChild(listItem);
document.getElementById(‘todo’).value="";
}

THE SOLUTION:
var todoList = document.getElementById(‘todoList’);
var additems = document.getElementById(‘addTodo’);
additems.onclick = function(){
var li = document.createElement(‘li’);
li.innerHTML = document.getElementById(“todo”).value;
todoList.appendChild(li);
document.getElementById(“todo”).value = " ";
}

  • Your unorderedlist variable is returning null instead of the list. Hint: getElementById is case sensitive.
  • You’re not appending the new list item to the list. Your code is trying to append the list item to itself, which doesn’t make sense

Let me know if this helps :slight_smile:

1 Like

Thank You.
The case sensitivity was indeed a big but subtle error to me.
and I thought I was appending to the parent list (unordered)

But may I ask if there is a specific way of coding these things:

  1. for coding onclick function: must I declare all those variables inside the function? Can I declare the variables outside and then do the processing inside the function?

  2. I believe that .getElementBy…() and .querySelector() perform same function. Is this true or what may be their differences?

For now, I’ll just answer your 2nd question. :smile:

Both types of methods are used to select a specific element on the page. The .getElementBy methods are more specific in that they will only take a class or id, depending on which one you use (getElementById, getElementsByClassName, etc). .querySelector is more general in that it will take tags, ids, classes. Being more general, querySelector doesn’t perform as well (is slower)