DOM Selectors and Events: Pure JS Shopping List (Custom list)

DOM Selectors allows you to select different elements from the document so you can manipulate with them. I will post only the most useful of them here.

As a part of my exercise after the lecture about DOM Selectors and DOM Events was creating a shopping list which you can edit like this:

  1. If you click on the list item, it toggles the specific class on and off.
  2. Add buttons next to each list item to delete the item when clicked on this button.
  3. BONUS: When adding a new list item, it automatically adds the delete button next to it.

While I have been working on this I decided to expand this task. I added a Clear List button and added a description if a list is empty. To make my list look nice I add some features as well.
That the list looks like:

Live Project – or you can check it on GitHub here and see the source here.

How to add a button to every li element of the ul list using JavaScript

I’ve created a function which is run every time when you click on Add button or press Enter. If the input field is not empty an item is added to an array. It simply creates a “li” element, appends text to that item and then appends it to a “ul” element.
The problem I faced to was how to add a button with click event listener in every li. I needed to add a delete function to this button as well.
Sounds challenging, isn’t it?
How did I do that?
I create a function for create an elements and add the button right after li element has been created:

function createListElement() {
	var listItem = document.createElement("li");
	var delButton = document.createElement("button");
	delButton.innerHTML = "Delete";
	input.value = ""; //clear input field
// -----------functions on cklick event (delete and toggle)
	function delItem() {
		var listNotEmpty = document.getElementsByClassName("delete-item");
		if (listNotEmpty.length === 0) {
	function itemDone() {
	delButton.addEventListener("click", delItem);
	listItem.addEventListener('click', itemDone);

This is basically it. Full JS and CSS, and HTML files you can find on GitHub (link I gave before).

Leave a Comment