-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent-delegation.js
78 lines (62 loc) · 2.23 KB
/
event-delegation.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// DOM Manipulation
// Event Delegation
// It allows users to append a SINGLE event listener
// to a parent element that adds it to all of its
// present AND future descendants that match a selector.
// document.querySelector("#football").addEventListener("click", function () {
// console.log("football is clicked");
// football.style.backgroundColor = "lightgrey";
// });
// football
// document.querySelector("#football").addEventListener("click", function (e) {
// console.log("football is clicked");
// const target = e.target;
// if (target.matches("li")) {
// target.style.backgroundColor = "lightgrey";
// }
// });
// // basketball
// document.querySelector("#basketball").addEventListener("click", function (e) {
// console.log("basketball is clicked");
// const target = e.target;
// if (target.matches("li")) {
// target.style.backgroundColor = "lightgrey";
// }
// });
// // boxing
// document.querySelector("#boxing").addEventListener("click", function (e) {
// console.log("boxing is clicked");
// const target = e.target;
// if (target.matches("li")) {
// target.style.backgroundColor = "lightgrey";
// }
// });
// // tennis
// document.querySelector("#tennis").addEventListener("click", function (e) {
// console.log("tennis is clicked");
// const target = e.target;
// if (target.matches("li")) {
// target.style.backgroundColor = "lightgrey";
// }
// });
// // golf
// document.querySelector("#golf").addEventListener("click", function (e) {
// console.log("golf is clicked");
// const target = e.target;
// if (target.matches("li")) {
// target.style.backgroundColor = "lightgrey";
// }
// });
// this time by using a SINGLE event listener to a parent element
document.querySelector("#sports").addEventListener("click", function (e) {
console.log(e.target.getAttribute("id") + " is clicked");
const target = e.target;
if (target.matches("li")) {
target.style.backgroundColor = "lightgrey";
}
});
const sports = document.querySelector("#sports");
const newSport = document.createElement("li");
newSport.innerText = "rugby";
newSport.setAttribute("id", "rugby");
sports.appendChild(newSport);