-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (51 loc) · 1.81 KB
/
index.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
//var a;
//1. API url
const url = "https://jsonplaceholder.typicode.com/users";
//2. Fetch users from the API url
function fetchUsers() {
//2.1 make use of the browser fetch API
fetch(url)
.then((response) => response.json())
.then((data) => {
//2.2 passing the user data to the renderUsers function
renderUsers(data);
});
}
//3. render the users in the DOM
function renderUsers(usersData) {
const ul = document.getElementById("user-list-container");
//3.1 render an li tag for each user
usersData.forEach((user, index) => {
const li = document.createElement("li");
li.innerHTML = `
<span>${index + 1}.</span>
<span class="name">${user.name}</span>
<span class="username">${user.username}</span>
`;
//3.2 append the current user li tag to the ul tag
ul.appendChild(li);
});
}
//4. add a search function to the DOM
function searchUsersByUsername() {
const input = document.getElementById("search");
const ul = document.getElementById("user-list-container");
const inputValue = input.value.toUpperCase();
const usersList = ul.querySelectorAll("li") // array of all the li tags
//loop through all the users and render the ones that matches the search
for(let index = 0; index < usersList.length; index++) {
const usernameSpanTag = usersList[index].querySelector(".username");
const nameSpanTag = usersList[index].querySelector(".name");
const usernameSpanTagValue = usernameSpanTag.innerText.toUpperCase();
const nameSpanTagValue = nameSpanTag.innerText.toUpperCase();
const isMatch = usernameSpanTagValue.indexOf(inputValue) > -1;
const isNameMatch = nameSpanTagValue.indexOf(inputValue) > -1;
if(isMatch || isNameMatch) {
usersList[index].style.display = "block";
}else {
usersList[index].style.display = "none";
}
}
}
//calling the fetch function
fetchUsers();