javascript - 如何删除除您单击的类(class)之外的所有类(class)?

标签 javascript class addclass removeclass toggleclass

当我单击链接时,此功能就会启动。它需要删除具有属性 [data-route] 的元素上的所有“.is-active”类。并在与我单击的链接连接的 [data-route] 元素上添加“.is-active”类。

    toggle: function(section){
        var sections = document.querySelectorAll('[data-route]');
        for (i = 0; i < sections.length; i++){
            document.querySelector('[data-route]').classList.remove('is-active');
        }
        document.querySelector(section).classList.add('is-active');
    }

但这行不通。它不会删除类(class)吗?

参见示例:http://jordypouw.github.io/myFED2/deeltoets1/index.html

附注它必须是原生 JavaScript。

最佳答案

toggle: function(section){
    var sections = document.querySelectorAll('[data-route]');
    for (i = 0; i < sections.length; i++){

        sections[i].classList.remove('is-active');

        // querySelectorAll return an array of dom elements, u can access them directly.

    }

    // I suppose in your case that ' section ' variable is the clicked element so :

    section.classList.add('is-active')

   // if not you have to store the dom element from the event, and add the class here.

}

关于javascript - 如何删除除您单击的类(class)之外的所有类(class)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26003283/

相关文章:

java - 可以在主类中初始化所有类吗?

Javascript 原型(prototype)、对象、构造函数??我很困惑

java - MySQL 和 SQLite 类

jquery - 在 id 中添加和删除类

jquery - 在元素中查找文本并将Class添加到Parent

javascript - 使用 jQuery 第二次单击元素类后开始操作

javascript - 我的脚本只适用于头等舱

javascript - 如何在ES6函数中触发onClick()函数?

javascript - FlotJS 工具提示扰乱了响应能力?

javascript - 如何使用 querySelector on 按名称选择输入元素?