Select and add class in javascript

前端 未结 5 1146
盖世英雄少女心
盖世英雄少女心 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:56

    Using plain javascript:

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

    Demo

    For older browsers you could use this:

    var list = [];
    var elements = document.getElementsByTagName('li');
    for (var i = 0; i < elements.length; ++i) {
        if (elements[i].className == "even" || elements[i].className == "odd") {
            list.push(elements[i]);
        };
    }
    for (var i = 0; i < list.length; ++i) {
        if (list[i].className.split(' ').indexOf('cf') < 0) {
            list[i].className = list[i].className + ' cf';
        }
    }
    

    Demo


    Using Mootools:

    $$('.itemRelated li').addClass('cf');
    

    Demo

    or if you want to target specific by Class:

    $$('li.even, li.odd').addClass('cf');
    

    Demo

提交回复
热议问题