Linked Questions

Popular Questions

I'm practicing some JS in codepen but my code doesn't seem to be working and I don't know why. I've already tried Googling and searching the question database in stack overflow. Here is all my code I'm using

    var newItemCounter = 1;
    var unList = document.getElementById("list");
    var button = document.getElementById("button");
    var headline = document.getElementById("headline");
    var listItems = document.getElementByID("list").getElementsByTagName("li");
    
    list.addEventListener("click", activateItem);
    
    function activateItem(e) {
      if (e.target.nodeName == "LI") {
        headline.innerHTML = e.target.innerHTML;
        for (i = 0; i < e.target.parentNode.children.length; i++) {
          e.target.parentNode.children[i].classList.remove("active");
        }
        e.target.classList.add("active");
      }
    }

    button.addEventListener("click", createNewItem);

    function createNewItem() {
      list.innerHTML += "<li>Something new " + newItemCounter + "</li>";
      newItemCounter++
    }
    .active{
      background-color:blue;
    }
    <h1 id="headline">Click a list item to replace this text.</h1>
    <button type="button" id="button">Add new item</button>
    <ul id="list">
      <li>First item</li>
      <li>Second item</li>
      <li>Third item</li>
      <li>Fourth item</li>
      <li>Fifth item</li>
    </ul>

Related Questions