-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
61 lines (51 loc) · 1.88 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const unFriendButtons = document.querySelectorAll("ol button");
// for (let button of unFriendButtons) {
// button.addEventListener("click", function (e) {
// e.target.parentElement.remove();
// });
// }
const addFriend = document.querySelector("#add-friend");
const newFriend = document.getElementById("first-name");
const friendList = document.querySelector("ol");
addFriend.addEventListener("submit", function (e) {
e.preventDefault();
let friendsName = newFriend.value;
const newListItem = document.createElement("li");
const newButton = document.createElement("button");
// // One way of solving the problem of added button not working ===> Not best solution
// newButton.addEventListener("click", function (e) {
// e.target.parentElement.remove();
// });
newButton.innerText = "Un-Friend";
newListItem.innerText = friendsName;
newListItem.append(newButton);
friendList.prepend(newListItem);
newFriend.value = "";
});
// Better solution is to add a delegate event listener
// friendList.addEventListener("click", function (e) {
// if (e.target.tagName === "BUTTON") {
// e.target.parentElement.remove();
// }
// });
// This can also be written as => we remove the work function
// friendList.addEventListener("click", (e) => {
// if (e.target.tagName === "BUTTON") {
// const listItem = e.target.closest("li");
// listItem.remove();
// }
// });
// It cans still be improved - where we use matches("button")
// friendList.addEventListener("click", (e) => {
// if (e.target.matches("button")) {
// e.target.parentElement.remove();
// }
// });
//It can further be improved and destructured to only focus on what we want form the event
friendList.addEventListener("click", ({ target }) => {
if (target.matches("button")) {
target.parentElement.remove();
} else if (target.matches("li")) {
target.classList.toggle("blocked");
}
});