Select and add class in javascript

前端 未结 5 1194
盖世英雄少女心
盖世英雄少女心 2021-02-05 10:12

Cross Platform if possible, how can I select classes in Javascript (but not Jquery please -MooTools is fine though-) on code that I can\'t add an ID? Specifically, I want to add

5条回答
  •  一生所求
    2021-02-05 10:37

    As others mention for selecting the elements you should use .querySelectorAll() method. DOM also provides classList API which supports adding, removing and toggling classes:

    var list, i;
    list = document.querySelectorAll('.even, .foo');
    for (i = 0; i < list.length; i++) {
        list[i].classList.add('cf');
    }
    

    As always IE9 and bellow don't support the API, if you want to support those browsers you can use a shim, MDN has one.

提交回复
热议问题