Messy function #3

by jacobwsmith

HTML

<div id="users">No users<div>

JavaScript

// function setupUserList(users) {
//   const container = document.getElementById("users");
//   container.innerHTML = "";
//   for (var i = 0; i < users.length; i++) {
//     var div = document.createElement("div");
//     div.className = "user";
//     div.innerText = users[i].name + " (" + users[i].email + ")";
//     div.onclick = function () {
//       alert("User selected: " + users[i].name);
//       div.style.backgroundColor = "lightgray";
//     };
//     container.appendChild(div);
//   }
//   if (users.length == 0) {
//     container.innerHTML = "No users found";
//   }
// }

function setupUserList(users) {
  const container = document.getElementById("users");
  if (!container) throw new Error("Missing #users container");
  container.innerHTML = "";
  if (!Array.isArray(users)) throw new Error("users must be an array");
  if (users.length === 0) {
    container.textContent = "No Users Found";
    return;
  }
  const fragment = document.createDocumentFragment();
  users.forEach((user) => {
    const div = document.createElement("div");
    div.className = "user";
    div.textContent = user.name + " (" + user.email + ")";
    div.addEventListener("click", () => {
      alert("User selected: " + user.name);
      document
        .querySelectorAll(".user")
        .forEach((u) => (u.style.backgroundColor = ""));
      div.style.backgroundColor = "lightgray";
    });
    fragment.appendChild(div);
  });
  container.appendChild(fragment);
}

const users = [
  {
    id: 1,
    name: "Jay Smith",
    email: "[email protected]",
  },
  {
    id: 2,
    name: "Larry Bird",
    email: "[email protected]",
  },
  {
    id: 3,
    name: "Michael Bolton",
    email: "[email protected]",
  },
];
setupUserList(users);