How do I add a class to a given element?

前端 未结 25 2263
清酒与你
清酒与你 2020-11-21 11:34

I have an element that already has a class:

相关标签:
25条回答
  • 2020-11-21 12:12

    In YUI, if you include yuidom, you can use

    YAHOO.util.Dom.addClass('div1','className');

    HTH

    0 讨论(0)
  • 2020-11-21 12:13

    Add Class

    • Cross Compatible

      In the following example we add a classname to the <body> element. This is IE-8 compatible.

      var a = document.body;
      a.classList ? a.classList.add('classname') : a.className += ' classname';
      

      This is shorthand for the following..

      var a = document.body;
      if (a.classList) {
          a.classList.add('wait');
      } else {
          a.className += ' wait';
      }
      

    • Performance

      If your more concerned with performance over cross-compatibility you can shorten it to the following which is 4% faster.

      var z = document.body;
      document.body.classList.add('wait');
      

    • Convenience

      Alternatively you could use jQuery but the resulting performance is significantly slower. 94% slower according to jsPerf

      $('body').addClass('wait');
      


    Removing the class

    • Performance

      Using jQuery selectively is the best method for removing a class if your concerned with performance

      var a = document.body, c = ' classname';
      $(a).removeClass(c);
      

    • Without jQuery it's 32% slower

      var a = document.body, c = ' classname';
      a.className = a.className.replace( c, '' );
      a.className = a.className + c;
      

    References

    1. jsPerf Test Case: Adding a Class
    2. jsPerf Test Case: Removing a Class

    Using Prototype

    Element("document.body").ClassNames.add("classname")
    Element("document.body").ClassNames.remove("classname")
    Element("document.body").ClassNames.set("classname")
    

    Using YUI

    YAHOO.util.Dom.hasClass(document.body,"classname")
    YAHOO.util.Dom.addClass(document.body,"classname")
    YAHOO.util.Dom.removeClass(document.body,"classname")
    
    0 讨论(0)
  • 2020-11-21 12:13

    If you don't want to use jQuery and want to support older browsers:

    function addClass(elem, clazz) {
        if (!elemHasClass(elem, clazz)) {
            elem.className += " " + clazz;
        }
    }
    
    function elemHasClass(elem, clazz) {
        return new RegExp("( |^)" + clazz + "( |$)").test(elem.className);
    }
    
    0 讨论(0)
  • 2020-11-21 12:14

    When the work I'm doing doesn't warrant using a library, I use these two functions:

    function addClass( classname, element ) {
        var cn = element.className;
        //test for existance
        if( cn.indexOf( classname ) != -1 ) {
            return;
        }
        //add a space if the element already has class
        if( cn != '' ) {
            classname = ' '+classname;
        }
        element.className = cn+classname;
    }
    
    function removeClass( classname, element ) {
        var cn = element.className;
        var rxp = new RegExp( "\\s?\\b"+classname+"\\b", "g" );
        cn = cn.replace( rxp, '' );
        element.className = cn;
    }
    
    0 讨论(0)
  • 2020-11-21 12:14

    You can use the API querySelector to select your element and then create a function with the element and the new classname as parameters. Using classlist for modern browsers, else for IE8. Then you can call the function after an event.

     //select the dom element
     var addClassVar = document.querySelector('.someclass');
    
     //define the addclass function
     var addClass = function(el,className){
       if (el.classList){
         el.classList.add(className);
       }
       else {
         el.className += ' ' + className;
      }
    };
    
    //call the function
    addClass(addClassVar, 'newClass');
    
    0 讨论(0)
  • 2020-11-21 12:16

    This js code works for me

    provides classname replacement

    var DDCdiv = hEle.getElementBy.....
    
    var cssCNs = DDCdiv.getAttribute('class');
    var Ta = cssCNs.split(' '); //split into an array
    for (var i=0; i< Ta.length;i++)
    {
        if (Ta[i] == 'visible'){
            Ta[i] = 'hidden';
            break;// quit for loop
        }
        else if (Ta[i] == 'hidden'){
            Ta[i] = 'visible';
        break;// quit for loop
        }
    }
    DDCdiv.setAttribute('class',Ta.join(' ') );  // Join array with space and set class name
    

    To add just use

    var cssCNs = DDCdiv.getAttribute('class');
    var Ta = cssCNs.split(' '); //split into an array
    Ta.push('New class name');
    // Ta.push('Another class name');//etc...
    DDCdiv.setAttribute('class',Ta.join(' ') );  // Join array with space and set class name
    

    To remove use

    var cssCNs = DDCdiv.getAttribute('class');
    var Ta = cssCNs.split(' '); //split into an array
    
    for (var i=0; i< Ta.length;i++)
    {
        if (Ta[i] == 'visible'){
            Ta.splice( i, 1 );
            break;// quit for loop
        }
    }
    DDCdiv.setAttribute('class',Ta.join(' ') );  // Join array with space and set class name
    

    Hope this is helpful to sombody

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