Select and add class in javascript

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

    Using some newer browser objects and methods.

    Pure JS: Details: old fashioned way, declaring stuff at the beginging than iterating in one big loop over elements with index 'i', no big science here. One thing is using classList object which is a smart way to add/remove/check classes inside arrays.

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

    Pure JS - 2: Details: document.querySelectorAll returns an array-like object which can be accessed via indexes but has no Array methods. Calling slice from Array.prototype returns an array of fetched elements instantly (probably the fastest NodeList -> Array conversion). Than you can use a .forEach method on newly created array object.

    Array.prototype.slice.call(document.querySelectorAll('.even','.odd'))
     .forEach(function(element) {
        element.classList.add('cf');
    });
    

    Pure JS - 3: Details: this is quite similar to v2, [].map is roughly that same as Array.prototype.map except here you declare an empty array to call the map method. It's shorter but more (ok little more) memory consuming. .map method runs a function on every element from the array and returns a new array (adding return in inside function would cause filling the returned values, here it's unused).

    [].map.call(document.querySelectorAll('.even','.odd'), function(element) {
        element.classList.add('cf');
    });
    

    Pick one and use ;)

提交回复
热议问题