DEV Community

Cover image for How to make your to-do list editable with basic JavaScript
Gabrielle Davidson
Gabrielle Davidson

Posted on • Edited on

How to make your to-do list editable with basic JavaScript

A to-do list is one of the first projects many developers create. The basic components are a way to add items and a way to delete them. This article is for those who have already implemented these basics and want to add the extra feature of being able to edit items once they are added.

Experiment with my to-do list here and if you'd like to inspect the code, you can find it on GitHub here. Note: it is only optimized for laptops at this time.

How to edit items

I wanted to be able to double click an item on the list in order to change it. Maybe I misspelled it or something. In my HTML, I used list elements for items. The high level idea was to temporarily replace the list element with an input element, type in something new, then change it back to a list element. To achieve this, I first added an event listener to each item when it was created:
Code to add an event listener to each item
Next, I created the editItem function. The list item you want to change is replaced by an input element with the same value. Then you are able to edit that value. These are the inner workings:
Steps for the 'editItem' function
The final step was to create the saveItem function in order to make my changes permanent. This basically reverses the steps above, replacing the input element and its new value with a new list element, though this time permanently (until you double click again, that is). Here's what it looks like:
Steps for the 'saveItem' function
That's it! If you happen to inspect it on GitHub, you may notice some slight variations in the code but none are relevant to making items editable. I hope this helps you make all your editable-to-do-list-dreams come true!

Top comments (4)

Collapse
 
meo3w profile image
Phil Hasenkamp

Thank you for sharing your knowledge! I learned a lot from this and had a breakthrough

Collapse
 
gabriellend profile image
Gabrielle Davidson

Omg the dream! I'm so glad it helped you!

Collapse
 
dannyengelman profile image
Danny Engelman

No need for prepend() and remove()
Modern browsers (everything but IE) support .replaceWith

developer.mozilla.org/en-US/docs/W...

Collapse
 
gabriellend profile image
Gabrielle Davidson

Cool, cool, didn't know that, thanks!