Skip to content
Advertisement

How to return the number of HTML list elements on change using an event listener in JavaScript?

My todo list appends every input value starting with the number of elements in the list. So, entering the first item “Do homework” outputs to “1. Do homework.” And the second input “Learn JS” outputs to “2. Learn JS.” However, when deleting an element in the middle of the list, the number adjacent to the item doesn’t adjust accordingly to the number of current list elements.

For example, if the output is:


1. Do homework
2. Learn JS
3. Practice piano

Deleting number 2 will return:


1. Do homework
3. Practice piano

Instead of the correct output:


1. Do homework
2. Practice piano

JavaScript
JavaScript
JavaScript

I have tried implementing this event listener and function with different variations of this but I have had no success:

JavaScript

Advertisement

Answer

For sure the number will not change, because you didn’t re-initialize the list text with new numeric values.

As @Barmar suggest, it would better to use “ol” element instead of “ul” which will output the correct numeric order of the list.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement