在 HTML 中自动添加或删除类

Ish*_*med 1 html javascript css foreach

我想在这些列表项中添加一个类,但条件是我在特定列表项中添加一个(活动)类

let getList=document.querySelectorAll("li")


getList.forEach(li=>{

    li.addEventListener("click", function(){
    
      li.classList.add("active")
    
    })
})
Run Code Online (Sandbox Code Playgroud)
.list-item{
  height:80px;
  width:70px;
  background-color:black
}

.list-item li{
  color:white
}
.active{
  border:5px soild blue;
  list-style:none; 
  color:orange;
  
}
Run Code Online (Sandbox Code Playgroud)
<body>
<ul class="list-item">
  
  <li>Apple</li>
  <li>Banana</li>
  <li>Orange</li>
  
</ul>


</body>
Run Code Online (Sandbox Code Playgroud)

必须自动删除列表标记中先前的活动类

dad*_*mes 7

您只需要从<li>已经设置了“活动”类的任何元素中删除它。否则,您最终会在多个元素上使用“活动”类。这是一种方法:

let getList=document.querySelectorAll("li")


getList.forEach(li=>{

    li.addEventListener("click", function(){
    
      // remove class from any currently active elements
      getList.forEach(li => { li.classList.remove("active"); });
    
      // then add the active class to the selected element
      li.classList.add("active")
    
    })
})
Run Code Online (Sandbox Code Playgroud)
.list-item{
  height:80px;
  width:70px;
  background-color:black
}

.list-item li{
  color:white
}
.active{
  border:5px soild blue;
  list-style:none; 
  color:orange;
  
}
Run Code Online (Sandbox Code Playgroud)
<body>
<ul class="list-item">
  
  <li>Apple</li>
  <li>Banana</li>
  <li>Orange</li>
  
</ul>


</body>
Run Code Online (Sandbox Code Playgroud)