How do I add a class to a given element?

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

I have an element that already has a class:

25条回答
  •  野的像风
    2020-11-21 11:53

    To add, remove or check element classes in a simple way:

    var uclass = {
        exists: function(elem,className){var p = new RegExp('(^| )'+className+'( |$)');return (elem.className && elem.className.match(p));},
        add: function(elem,className){if(uclass.exists(elem,className)){return true;}elem.className += ' '+className;},
        remove: function(elem,className){var c = elem.className;var p = new RegExp('(^| )'+className+'( |$)');c = c.replace(p,' ').replace(/  /g,' ');elem.className = c;}
    };
    
    var elem = document.getElementById('someElem');
    //Add a class, only if not exists yet.
    uclass.add(elem,'someClass');
    //Remove class
    uclass.remove(elem,'someClass');
    

提交回复
热议问题