Create a user list with clickable names and email addresses

by jacobwsmith

HTML

<div id="users"><div>

JavaScript

function setupUserList(users) {
  const container = document.getElementById("users");
  if(!container) throw new Error('no div with #users')
  container.innerHTML = "";
  if (users.length == 0) {
    container.textContent = "No users found";
    return;
  }
  const fragement = document.createDocumentFragment();
  users.forEach(user => {
    var div = document.createElement("div");
    div.className = "user";
    div.textContent = user.name + " (" + user.email + ")";
    // fix
    div.addEventListener('click', () => {
      alert("User selected: " + user.name);
      // todo: remove all styles? 
      div.style.backgroundColor = "lightgray";
    })
    fragement.appendChild(div);
  });
  container.appendChild(fragement)
}

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);