How to close list items with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

To close list items with JavaScript, the code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   * {
      box-sizing: border-box;
   }
   ul {
      list-style-type: none;
      padding: 0;
      margin: 0;
   }
   ul li {
      border: 1px solid rgb(221, 221, 221);
      background-color: #5a5cec;
      color: white;
      padding: 12px;
      text-decoration: none;
      font-size: 18px;
      display: block;
      position: relative;
      font-weight: 500;
   }
   ul li:hover {
      background-color: rgb(43, 0, 145);
   }
   .close {
      cursor: pointer;
      position: absolute;
      top: 50%;
      right: 0%;
      padding: 12px 16px;
      transform: translate(0%, -50%);
   }
   .close:hover {
      background: red;
   }
</style>
</head>
<body>
<h1>Closable List Items Example</h1>
<h2>Click 'x' on the list items to close them</h2>
<ul>
<li>Cat<span class="close">×</span></li>
<li>Lion<span class="close">×</span></li>
<li>Tiger<span class="close">×</span></li>
<li>Leopard<span class="close">×</span></li>
<li>Cheetah<span class="close">×</span></li>
</ul>
<script>
   var closebtns = document.querySelectorAll(".close");
   Array.from(closebtns).forEach(item => {
      item.addEventListener("click", () => {
         item.parentElement.style.display = "none";
      });
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘x’ on some items −

raja
Published on 12-May-2020 11:19:18
Advertisements