Using link to remove list items from page using HTML5 and Javascript

37 views Asked by At

I am trying to create a link that will remove two list items from an ul that are above the link. I am new at this and appreciate any help!

1

There are 1 answers

0
ras592 On

The question is pretty vague, but this is how I would achieve something like this in JavaScript with a link.

HTML:

<ul id="my_list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
<a href="#" id="delete_items">click to remove item</a>

JavaScript:

function deleteItems() {
   var item_list = document.querySelectorAll("ul#my_list li");
   if (item_list.length >= 2) { 
     item_list[0].parentNode.removeChild(item_list[0]);
     item_list[1].parentNode.removeChild(item_list[1]);
   } else if (item_list.length == 1) {
     item_list[0].parentNode.removeChild(item_list[0]);
   }
}

var delete_link = document.getElementById('delete_items');
delete_link.onclick = deleteItems;

Codepen link here.