[英]Add and remove classes when click on multiple div using javascript
I am actually trying to add class (Selected) to the label when clicked and remove Class from neighbour label.我实际上试图在单击时将类(选定)添加到标签并从邻居标签中删除类。
Issue is it doesn't work when there is 2 div, the below code only work on the 1st Div or when i click on the label of the second label, first label active gets removed问题是当有 2 个 div 时它不起作用,下面的代码仅适用于第一个 Div 或当我单击第二个标签的标签时,第一个活动标签被删除
const menuLis = document.querySelectorAll(".top-nav > label"); for (let label of menuLis) { label.addEventListener("click", function(){ // 1. Remove Class from All Lis for (let label of menuLis) { label.classList.remove('selected'); } // 2. Add Class to Relevant Li this.classList.add('selected'); }); }
.selected{color:red}
<div class="grid-item"> <section> <div class='top-nav'> <label>Coffee</label> <label>Tea</label> <label>Milk</label> </div> </section> </div> <br><br> <div class="grid-item"> <section> <div class='top-nav'> <label>Coffee</label> <label>Tea</label> <label>Milk</label> </div> </section> </div>
Thanks谢谢
You're removing the class from all the items in menuLis
.您正在从menuLis
所有项目中menuLis
。 You should get a list of just the labels in the current .top-nav
section and remove the class from them.您应该获得当前.top-nav
部分中仅包含标签的列表,并从中删除类。
const menuLis = document.querySelectorAll(".top-nav > label"); for (let label of menuLis) { label.addEventListener("click", function(){ let container = this.closest('.top-nav'); let curMenuLis = container.querySelectorAll("label"); // 1. Remove Class from All Lis for (let label of curMenuLis) { label.classList.remove('selected'); } // 2. Add Class to Relevant Li this.classList.add('selected'); }); }
.selected{color:red}
<div class="grid-item"> <section> <div class='top-nav'> <label>Coffee</label> <label>Tea</label> <label>Milk</label> </div> </section> </div> <br><br> <div class="grid-item"> <section> <div class='top-nav'> <label>Coffee</label> <label>Tea</label> <label>Milk</label> </div> </section> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.