Toggle list items green in todo list

Advertisements

I’m making a simple todo list and want to turn the background color of the list items green when the "DONE" button is clicked. I got the first item to turn green but the others won’t. I’m using plain JavaScript. Here is my HTML and JavaScript code:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Get Stuff Done</title>
  <link rel="stylesheet" href="todo.css" type="text/css">
  <script src="todo.js" type="text/javascript"></script>
</head>

<body>
  <div class="container">
    <header>
      <p>
        <h1 id="title">
          Todo list
        </h1>
        <h2 id="date">

        </h2>
      </p>
      <form name="myForm" method="post" action="">
        <input type="text" id="add" name="addNew">
        <button name="sumbitBtn" type="button" class="addBtn" onclick="addItem()">add</button>
        <div>
          <ul id="unList">
          </ul>
      </form>
    </header>
    </div>
  </div>
</body>

</html>

const list = [] function addItem() { task = document.getElementById(‘add’).value; list.push(task); document.getElementById(‘unList’).innerHTML += "
" + task + "" + ‘done’ + "" + "

" } function change() { document.getElementById(‘item’).style.backgroundColor = ‘green’; }

>Solution :

You "can" have multiple elements with the same id, but you should never do it, because when you try to get elements using that id, only the first element will be returned.

I am passing the button to the change (using this), and acessing the parentNode with is the <li>:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Get Stuff Done</title>
  <link rel="stylesheet" href="todo.css" type="text/css">
  <script type="text/javascript">

  const list = [];
  
  function addItem() { 
  task = document.getElementById('add').value; 
  list.push(task); document.getElementById('unList').innerHTML += `
      <li> ${task} <button type='button' onclick='change(this)'>done</button></li>`
  } 
  
  function change(element) { 
     element.parentNode.style.backgroundColor = 'green'; 
  }

  </script>
</head>

<body>
  <div class="container">
    <header>
      <p>
        <h1 id="title">
          Todo list
        </h1>
        <h2 id="date">

        </h2>
      </p>
      <form name="myForm" method="post" action="">
        <input type="text" id="add" name="addNew">
        <button name="sumbitBtn" type="button" class="addBtn" onclick="addItem()">add</button>
        <div>
          <ul id="unList">
          </ul>
      </form>
    </header>
    </div>
  </div>
</body>

</html>

Leave a ReplyCancel reply