0

Unable to add new elements

I'm trying to create to-do list. Everything is set, all the is left is to create a new element and add it to a container element for the items in the list when the add item button is clicked. I tried doing it this way: let allItems = document.querySelector('.item-group) let addItemButton = document.querySelector('#add-item) addItemButton.onclick = addItems() function addItems() { let newItem = document.createElement('div') newItem.className = 'new-item' allItems.insertBefore(newItem, allItem.lastElementChild) } The newly div is supposed to appear inside the allItems element with the specified style for that class but for some reasons it doesn't. How can I do this correctly?

1st Jan 2021, 5:12 PM
Logos
Logos - avatar
1 Answer
+ 1
There are a lot of mistakes in your code. Also, from the next time, please copy your code and save it in the code playground and then attach it to the question so that referencing the line numbers is easier. For now, every line number I mention will be counted from the line `let allItems = ....`, also counting the blank lines 1. In line 1, there is no closing single-quote for the string 2. In line 2, the same error as line 1 3. onClick on any element has to be a *function* that will be called when the event occurs. Here on line 4, you are assigning the *called* function, that is, the value returned after calling the function, to addItemButton.onClick, instead of the function itself. To fix it, don't call the function `addItems`, simply assign it 4. In line 9, you have written `allItem` instead of `allItems`
1st Jan 2021, 5:44 PM
XXX
XXX - avatar