How to create: closable list items

Learn how to close list items using JavaScript.

Closable list items

Click on the "×" symbol on the right side of the list item to close/hide it.

Try It Yourself

How to create closable list items

Step 1 - Add HTML:

<ul>
  <li>Adele</li>
  <li>Agnes<span class="close">x</span></li>
  <li>Billy<span class="close">x</span></li>
  <li>Bob<span class="close">x</span></li>
  <li>Calvin<span class="close">x</span></li>
  <li>Christina<span class="close">x</span></li>
  <li>Cindy</li>
</ul>

Second step - Add CSS:

* {
  box-sizing: border-box;
}
/* Set list style (remove margin and bullet points, etc.) */
ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}
/* Set the style of list items */
ul li {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double border */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block;
  position: relative;
}
/* Add light grey background color on hover */
ul li:hover {
  background-color: #eee;
}
/* Set the style of the close button (span) */
.close {
  cursor: pointer;
  position: absolute;
  top: 50%;
  right: 0%;
  padding: 12px 16px;
  transform: translate(0%, -50%);
}
.close:hover {background: #bbb;}

Third step - Add JavaScript:

// Get all elements with class="close"
var closebtns = document.getElementsByClassName("close");
var i;
// Traverse elements and hide the parent element on click
for (i = 0; i < closebtns.length; i++) {
  closebtns[i].addEventListener("click", function() {
    this.parentElement.style.display = 'none';
  });
}

Try It Yourself