How do I add a class to a given element?

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

I have an element that already has a class:

25条回答
  •  温柔的废话
    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

提交回复
热议问题