0

I have a simple ul list, as can be seen below:

<div class="container">
  <div class="row">
    <div class="col">
      <h1>My Favorite Meals <span>(1)</span></h1>
      <hr>

      <ul>
        <li class="selected">Spaghetti</li>
        <li>Curry &amp; Rice</li>
        <li>Burrito</li>
        <li>Soup</li>
        <li>Something Else</li>
      </ul>
    </div>
  </div>
</div>

What I want to do, is to make this list clickable. So that when you click on one of the Lis, the background color changes, and the selected li will also be assigned a new class.

My JS code isn't working:

var ul = document.getElementById("foo")
var items = ul.getElementsByTagName("li")

for (var i = 0; i < items.length; ++i) {
  // do something with items[i], which is a <li> element
  var current = items[i]
  current.addEventListener("click", onClick)
  var onClick = function() {
    current.style.backgroundColor = "red"
}
}
snuffydave
  • 47
  • 6
  • You need javascript and the dom for this to add CSS classes dynamically. I reccomend you create a js file and write a function that will handle clicks on
  • elements within the
      as well as prepopulate them with unique ID's potentially by index or text content.
  • – Omar Oct 04 '20 at 04:47
  • There is no foo id on ul – sarkiroka Oct 04 '20 at 05:02