MicSparrow
MicSparrow

Reputation: 23

Dynamically hide objects with the same class in pure JS

I have a problem with dynamically hiding objects that share the same class in pure JS.

In the "render" function responsible for presenting the table with contents of the site I wrote this fragment.

    tasklist.forEach((item) => {
      const table = `<tr>
        <td>${item.task}</td>
        <td>${item.date}</td>
        <td>${item.priority}</td>
        <td><a class="delete">delete</a></td>
        </tr>`;
      parent2.insertAdjacentHTML("afterbegin", table);
       if (item.priority == "normal") {
            item.priority.className = "nonpriority-set";
      }
    });

The last part has to add class "nonpriority-set" to all elements that (after the "priorityCheck" function is run) are detected as "normal" tasks.

 function priorityCheck() {
      if (Taskpriority.checked === true) {
        Taskpriority.value = "priority"
      } else {
        Taskpriority.value = "normal"
      }
    }

This function is tasked with hiding the "tasks" with the priority set to "normal".

  function Priorities() {
    const priorityButton = document.querySelector(".priority");
    priorityButton.addEventListener("click", showPriorities);

    function showPriorities() {
      let prts = document.querySelectorAll(".nonpriority-set");
      prts.style.visibility = 'hidden';
      render();
    }
  }
  Priorities();

However it is not doing what it's tasked - hiding the "normal"-labelled tasks and leaving only priorities. What should I change in this code?

let tasklist = [];
// checkLocalStorage();

function initializeWebsite() {

  const Plus2 = document.querySelector("#plus2");
  Plus2.addEventListener("click", append);

  const parent = document.querySelector(".addtask");

  const input = document.createElement("input");
  input.type = "text";
  input.className = "task-form";
  input.placeholder = "Write your task here...";

  const checker = document.createElement("input");
  checker.type = "checkbox";
  checker.className = "check-box";
  checker.title = "Done/undone";

  const calendar = document.createElement("input");
  calendar.type = "datetime-local";
  calendar.className = "date";

  const applyButton = document.createElement("button");
  applyButton.textContent = "Apply";
  applyButton.className = "button1";

  const cancelButton = document.createElement("button");
  cancelButton.textContent = "Cancel";
  cancelButton.className = "button2";

  const lineBreak = document.createElement('br');

  function append() {
    parent.appendChild(input);
    parent.appendChild(calendar);
    parent.appendChild(checker);
    parent.appendChild(lineBreak);
    parent.appendChild(applyButton);
    parent.appendChild(cancelButton);
    const removePrompt = document.querySelector(".button2");
    const addPrompt = document.querySelector(".button1");
    removePrompt.addEventListener("click", abort);
    addPrompt.addEventListener("click", apply);
  }

  function abort() {
    parent.removeChild(input);
    parent.removeChild(checker);
    parent.removeChild(calendar);
    parent.removeChild(lineBreak);
    parent.removeChild(applyButton);
    parent.removeChild(cancelButton);
  }
}
initializeWebsite();
start();
render();

class Tasks {
  constructor(task, date, priority) {
    this.task = task;
    this.date = date;
    this.priority = priority;
  }
}

function apply() {
  const Tasktask = document.querySelector(".task-form");
  const Taskdate = document.querySelector(".date");
  const Taskpriority = document.querySelector(".check-box");

  function prevent() {
    if (Tasktask.value.length === 0 || Taskdate.value === "") {
      alert("Fields cannot be empty!");
    } else {
      pushed();
      render();
      clear();
    }
  }
  prevent();

  function pushed() {
    priorityCheck();
    let newTasks = new Tasks(Tasktask.value, Taskdate.value, Taskpriority.value);
    tasklist.push(newTasks);
    addLocalStorage();
  }

  function priorityCheck() {
    if (Taskpriority.checked === true) {
      Taskpriority.value = "priority"
    } else {
      Taskpriority.value = "normal"
    }
  }

  function clear() {
    Tasktask.value = "";
    Taskdate.value = "";
    Taskpriority.checked = false;
  }
}

function addLocalStorage() {
  // localStorage.setItem("tasklist", JSON.stringify(tasklist));
}

function checkLocalStorage() {
  if (localStorage.getItem("tasklist")) {
    tasklist = JSON.parse(localStorage.getItem("tasklist"));
  } else {
    tasklist = [];
  }
}

function render() {
  const parent2 = document.querySelector(".table-body");
  parent2.innerHTML = "";
  tasklist.forEach((item) => {
    const table = `<tr>
        <td>${item.task}</td>
        <td>${item.date}</td>
        <td>${item.priority}</td>
        <td><a class="delete">delete</a></td>
        </tr>`;
    parent2.insertAdjacentHTML("afterbegin", table);
    if (item.priority == "normal") {
      item.priority.className = "nonpriority-set";
    }
  });
}

function deleteTask(current) {
  tasklist.splice(current, 1);
}

function findTask(taskArray, task) {
  if (taskArray.length === 0 || taskArray === null) {
    return;
  }
  for (let item of taskArray)
    if (item.task === task) {
      return taskArray.indexOf(item);
    }
}

function start() {
  const Table = document.querySelector("table").addEventListener("click", (e) => {
    const currentTarget = e.target.parentNode.parentNode.childNodes[1];
    if (e.target.innerHTML == "delete") {
      if (confirm(`Are you sure you want to delete ${currentTarget.innerText}?`))
        deleteTask(findTask(tasklist, currentTarget.innerText));
    }
    addLocalStorage();
    render();
  });
}

function Priorities() {
  const priorityButton = document.querySelector(".priority");
  priorityButton.addEventListener("click", showPriorities);

  function showPriorities() {
    let prts = document.querySelectorAll(".nonpriority-set");
    prts.style.visibility = 'hidden';
    render();
  }
}
Priorities();
* {
  box-sizing: border-box;
}

body {
  font-family: Arial, Helvetica, sans-serif;
}

header {
  background-color: #000000;
  padding: 15px;
  text-align: left;
  font-size: 25px;
  color: #ffffff;
}

header img {
  display: inline;
  height: 50px;
  width: 50px;
  padding-top: 12px;
  padding-right: 8px;
}

h2 {
  display: inline;
}

section {
  display: -webkit-flex;
  display: flex;
}

nav {
  -webkit-flex: 1;
  -ms-flex: 1;
  flex: 1;
  background: #ccc;
  padding: 20px;
}

nav ul {
  list-style-type: none;
  padding: 0;
}

nav a {
  text-decoration: none;
  font-size: 20px;
  font-weight: bold;
  color: #000000;
}

nav a:hover {
  color: #f1f1f1;
}

.preaddtask {
  -webkit-flex: 2;
  -ms-flex: 2;
  flex: 2;
  text-align: center;
  padding: 20px;
  margin: 20px;
}

.addtask {
  -webkit-flex: 2;
  -ms-flex: 2;
  flex: 2;
  text-align: center;
  padding: 30px;
  margin: 20px;
  margin-top: 30px;
}

#plus {
  font-size: 25px;
}

#plus2 {
  font-size: 55px;
  text-align: center;
  padding-left: 10px;
  margin: 5px;
  color: #b3b3b3;
  cursor: pointer;
}

#plus2:hover {
  color: #000000;
  transform: scale(1.1);
}

.task-info {
  color: #000000;
  text-align: center;
  padding: 5px;
  margin: 10px;
  font-size: 20px;
  font-weight: bold;
}

.taskadded {
  -webkit-flex: 3;
  -ms-flex: 3;
  flex: 3;
  background-color: #f1f1f1;
  padding: 10px;
  text-align: center;
}

table {
  margin: 0 auto;
}

th {
  padding: 15px;
}

.addproject {
  -webkit-flex: 3;
  -ms-flex: 3;
  flex: 3;
  background-color: #f1f1f1;
  padding: 10px;
  text-align: center;
}

hr {
  border: 1px solid #d9d9d9;
}

footer {
  background-color: #ffffff;
  padding: 10px;
  text-align: center;
  color: #000000;
}

@media (max-width: 600px) {
  section {
    -webkit-flex-direction: column;
    flex-direction: column;
  }
}

.task-form {
  display: inline-block;
  margin: 5px;
  border: 1px solid #000000;
  width: 200px;
  height: 30px;
}

button {
  height: 30px;
  width: 100px;
  display: inline;
  font-weight: bold;
  padding: 5px;
  background: #a6a6a6;
  border: 1px solid #000000;
}

.button1,
.button2 {
  margin: 5px;
  cursor: pointer;
}

.check-box {
  -webkit-box-shadow: 0px 0px 1px 0px rgb(0, 0, 0);
  border: 1px solid #000000;
  margin: 5px;
  display: inline-block;
  vertical-align: middle;
  height: 30px;
  width: 30px;
  cursor: pointer;
}

.date {
  display: inline-block;
  margin: 5px;
  cursor: pointer;
}

.delete {
  cursor: pointer;
  text-decoration: underline;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>To-do list</title>
  <link rel="stylesheet" href="styles.css" />
</head>

<body>

  <div class="container">

    <div class="headerwrapper">
      <header>
        <img src="https://icon-library.com/images/white-check-icon/white-check-icon-16.jpg" alt="logo">
        <h2>To-do list</h2>
      </header>
    </div>
    <div class="sectionwrapper">
      <section>
        <div class="navdiv">
          <nav>
            <ul>
              <li><a href="#">All tasks</a></li>
              <li><a href="#">Today</a></li>
              <li><a href="#">This week</a></li>
              <li><a href="#" class="priority">Priorities</a></li>
              <li><a href="#" title="Click to add a new project" id="plus">+</a></li>
            </ul>
          </nav>
        </div>
        <div class="preaddtask">
          <p title="Click to add a new task" id="plus2">+</p>
          <p class="task-info">Click this button to add a new task</p>
        </div>
        <div class="addtask">
        </div>
      </section>

      <section>
        <div class="taskadded">
          <table class="task-table">
            <tr>
              <th>Task name</th>
              <th>Date</th>
              <th>Priority</th>
              <th></th>
            </tr>
            <tbody class="table-body"></tbody>
          </table>
        </div>
      </section>
      <hr>
      <section>
        <div class="addproject">
        </div>
      </section>
    </div>
  </div>

  <div class="end">

    <footer>
      <hr>Made by <a href="https://www.github.com/micsparrow">MicSparrow</a>, 2021
      <hr>
    </footer>
  </div>
  <script src="main.js" defer></script>

</body>

</html>

Link to JSFiddle for better understanding the full code - here. Thanks in advance for your help.

Upvotes: 1

Views: 48

Answers (1)

Pauline
Pauline

Reputation: 151

prts is an array-like NodeList. To change the style of elements contained in that list, you need to iterate over it using NodeList.prototype.forEach(el, handler) or for..of:

prts.forEach(el=> el.style.visibility = 'hidden');

or

for (const el of prts) { el.style.visibility = 'hidden'; }

Upvotes: 1

Related Questions