Skip to content

Instantly share code, notes, and snippets.

@QuocCao-dev
Last active March 26, 2024 14:21
Show Gist options
  • Save QuocCao-dev/5f65e6fe58574ae79bc840c90494ab90 to your computer and use it in GitHub Desktop.
Save QuocCao-dev/5f65e6fe58574ae79bc840c90494ab90 to your computer and use it in GitHub Desktop.
shop list
const itemForm = document.getElementById("item-form");
const itemInput = document.getElementById("item-input");
const itemList = document.getElementById("item-list");
const clearBtn = document.getElementById("clear");
const filterInput = document.getElementById("filter");
const liInItems = document.querySelectorAll(".items > li");
function createElement(tag, className, text) {
const elm = document.createElement(tag);
if (className) elm.className = className;
if (text) elm.innerText = text;
return elm;
}
function createLiDOM(liValue) {
let liTag = createElement("li", "", liValue);
let btnTag = createElement("button", "remove-item btn-link text-red");
let iTag = createElement("i", "fa-solid fa-xmark");
liTag.appendChild(btnTag);
btnTag.appendChild(iTag);
return liTag;
}
function addItem(evt) {
evt.preventDefault();
const value = itemInput.value;
if (value === "") return;
let liTag = createLiDOM(value);
itemList.appendChild(liTag);
itemInput.value = "";
}
function removeItem(evt) {
if (evt.target.parentElement.classList.contains("remove-item")) {
evt.target.parentElement.parentElement.remove();
}
}
itemForm.addEventListener("submit", function (event) {
addItem(event);
});
itemList.addEventListener("click", function (event) {
removeItem(event);
});
clearBtn.addEventListener("click", function () {
itemList.innerHTML = "";
});
filterInput.addEventListener("input", function (event) {
const searchValue = event.currentTarget.value.toLowerCase();
liInItems.forEach((item) => {
const checkItem = item.innerText.toLowerCase().includes(searchValue);
item.style.display = checkItem ? "flex" : "none";
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment