如何删除除单击的元素之外的所有其他元素的类

时间:2019-02-01 09:37:56

标签: javascript events classname

你好,我想删除除单击元素之外的所有其他元素的类。

到目前为止,我的代码看起来像这样,但是我找不到解决方法

const elements = document.querySelectorAll(".element");

function toggleOpen() {
    this.classList.toggle('open');
    elemets.forEach(ele => {
        ele.classList.remove('open'); // buts this removes the class from all 
       the elements I am looking for something that removes the class on just 
       the other one element containing the class except on the clicked one.
    }) 
}

elements.forEach(ele => ele.addEventListener('click', toggleOpen));

1 个答案:

答案 0 :(得分:2)

您真的很亲密,只需在forEach循环中使用Path clipPath = new Path(); RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight()); clipPath.addRoundRect(rect, radius, radius, Path.Direction.CW); canvas.clipPath(clipPath); 子句即可通过与if进行比较来跳过您单击的元素,而且,您在函数中输入有错字:

this
const elements = document.querySelectorAll('.element');

function toggleOpen() {
    this.classList.toggle('open');
    elements.forEach(ele => {
        if (ele !== this) ele.classList.remove('open');
    });
}

elements.forEach(ele => ele.addEventListener('click', toggleOpen));
.element { color: red; }
.open { color: green; }