Select and add class in javascript

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

    0 讨论(0)
  • 2021-02-05 10:39

    querySelectorAll is supported in IE8, getElementsByClassName is not, which does not get two classes at the same time either. None of them work in iE7, but who cares.

    Then it's just a matter of iterating and adding to the className property.

    var list = document.querySelectorAll(".even, .odd");
    for (var i = list.length; i--;) {
        list[i].className = list[i].className + ' cf';
    }
    

    FIDDLE

    0 讨论(0)
  • 2021-02-05 10:42

    I know this is old, but is there any reason not to simply do this (besides potential browser support issues)?

    document.querySelectorAll("li.even, li.odd").forEach((el) => {
        el.classList.add('cf');
    });
    

    Support: https://caniuse.com/#feat=es5

    0 讨论(0)
  • 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 ;)

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题