JavaScript CSS how to add and remove multiple CSS classes to an element

前端 未结 14 1893
迷失自我
迷失自我 2020-12-07 21:46

How can assign multiple css classes to an html element through javascript without using any libraries?

相关标签:
14条回答
  • 2020-12-07 22:29

    Here's a simpler method to add multiple classes via classList (supported by all modern browsers, as noted in other answers here):

    div.classList.add('foo', 'bar'); // add multiple classes

    From: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Examples

    If you have an array of class names to add to an element, you can use the ES6 spread operator to pass them all into classList.add() via this one-liner:

    let classesToAdd = [ 'foo', 'bar', 'baz' ];
    div.classList.add(...classesToAdd);
    

    Note that not all browsers support ES6 natively yet, so as with any other ES6 answer you'll probably want to use a transpiler like Babel, or just stick with ES5 and use a solution like @LayZee's above.

    0 讨论(0)
  • 2020-12-07 22:29

    just use this

    element.getAttributeNode("class").value += " antherClass";
    

    take care about Space to avoid mix old class with new class

    0 讨论(0)
  • 2020-12-07 22:31

    In modern browsers, the classList API is supported.

    This allows for a (vanilla) JavaScript function like this:

    var addClasses;
    
    addClasses = function (selector, classArray) {
        'use strict';
    
        var className, element, elements, i, j, lengthI, lengthJ;
    
        elements = document.querySelectorAll(selector);
    
        // Loop through the elements
        for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
            element = elements[i];
    
            // Loop through the array of classes to add one class at a time
            for (j = 0, lengthJ = classArray.length; j < lengthJ; j += 1) {
                className = classArray[j];
    
                element.classList.add(className);
            }
        }
    };
    

    Modern browsers (not IE) support passing multiple arguments to the classList::add function, which would remove the need for the nested loop, simplifying the function a bit:

    var addClasses;
    
    addClasses = function (selector, classArray) {
        'use strict';
    
        var classList, className, element, elements, i, j, lengthI, lengthJ;
    
        elements = document.querySelectorAll(selector);
    
        // Loop through the elements
        for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
            element = elements[i];
            classList = element.classList;
    
            // Pass the array of classes as multiple arguments to classList::add
            classList.add.apply(classList, classArray);
        }
    };
    

    Usage

    addClasses('.button', ['large', 'primary']);
    

    Functional version

    var addClassesToElement, addClassesToSelection;
    
    addClassesToElement = function (element, classArray) {
        'use strict';
    
        classArray.forEach(function (className) {
           element.classList.add(className);
        });
    };
    
    addClassesToSelection = function (selector, classArray) {
        'use strict';
    
        // Use Array::forEach on NodeList to iterate over results.
        // Okay, since we’re not trying to modify the NodeList.
        Array.prototype.forEach.call(document.querySelectorAll(selector), function (element) {
            addClassesToElement(element, classArray)
        });
    };
    
    // Usage
    addClassesToSelection('.button', ['button', 'button--primary', 'button--large'])
    

    The classList::add function will prevent multiple instances of the same CSS class as opposed to some of the previous answers.

    Resources on the classList API:

    • Can I use
    • MDN
    • David Walsh
    • HTML5 Doctor
    0 讨论(0)
  • 2020-12-07 22:37

    Perhaps:

    document.getElementById("myEle").className = "class1 class2";
    

    Not tested, but should work.

    0 讨论(0)
  • 2020-12-07 22:42
    var el = document.getElementsByClassName('myclass')
    
    el[0].classList.add('newclass');
    
    el[0].classList.remove('newclass');
    

    To find whether the class exists or not, use:

    el[0].classList.contains('newclass'); // this will return true or false 
    

    Browser support IE8+

    0 讨论(0)
  • 2020-12-07 22:45

    guaranteed to work on new browsers. the old className way may not, since it's deprecated.

    <element class="oneclass" />
    
    element.setAttribute('class', element.getAttribute('class') + ' another');
    alert(element.getAttribute('class')); // oneclass another
    
    0 讨论(0)
提交回复
热议问题