skip to Main Content

I’m trying to add a CSS class to a clicked li element in a ul list, but I’m having a problem where the CSS class is being added to multiple li elements instead of the one that was clicked. I want to click on a li, the color applies to the li that clicked Here’s the code I’m using:

const lis = document.querySelectorAll('.li');
lis.forEach((li)=>{
    li.addEventListener("click",()=>{
        li.classList.add('active')
    })
})
ul {
    list-style: none;
    display: flex;
    justify-content: center;
  }
  
  .li {
    margin: 0 0.5rem;
    padding: 0.5rem 0.75rem;
    border: 1px solid black;
    border-radius: 0.25rem;
    cursor: pointer;
  }
  
  .li:hover {
    background-color: #ccc;
  }
  .li.active{
    color: red;
  }
<body>
    <ul>
        <li class="li">1</li>
        <li class="li">3</li>
        <li class="li">4</li>
        <li class="li">5</li>
        <li class="li">6</li>
        <li class="li">7</li>
    </ul>
</body>

When I click on an li element, the ‘active’ class is being added to all li elements in the list who has already clicked, instead of just the one that was clicked. How can I modify this code to ensure that the ‘active’ class is only added to the clicked li element and not to any others in the list?

Any help or guidance would be greatly appreciated. Thank you!


Please signup or login to give your own answer.
Back To Top
Search