Simple implementation of adding multiple classes to elements by javascript
<html> <head> <style type="text/css"> .div2{ font-size:16px; color:orange; } .div3{ font-size:20px; color:blue; } <style> <script type="text/javascript"> [1] Directly assign the style to className var odiv=document.getElementById('div1'); odiv.className= div3 //In this way we will get class="div3" and will directly overwrite the div2 style; [2] Use accumulation to assign the value to className var odiv=document.getElementById('div1'); odiv.className+=" "+div3 //There is a gap between the style and the style, so add an empty string to separate it // This can be added normally, but when we add the style, we have to consider whether it has the same style before. If we add it, it will become a burden, for example class="div2 div3 div3"; [3] Check whether the style has the same style before var odiv=document.getElementById('div1'); function hasClass(element,csName){ element.className.match(RegExp('(//s|^)'+csName+'(//s|$)')); //Use regular detection to see if there is the same style} [4] Based on [3], we can judge the style to the element. var odiv=document.getElementById('div1'); function hasClass(element,csName){ return element.className.match(RegExp('(//s|^)'+csName+'(//s|$)')); //Use regular detection to see if there is the same style} function addClass(element,csName){ if(!hasClass(element,csName)){ element.className+=' '+csName; } addClass(odiv,'div3'); //This way you can add styles to the element flexibly; [Element Delete specified style] //Same thing to make judgment first, and delete var odiv=document.getElementById('div1'); function hasClass(element,csName){ return element.className.match(RegExp('(//s|^)'+csName+'(//s|$)')); //Use regular detection to see if there is the same style} function deleteClass(element,csName){ if(!hasClass(element,csName)){ element.className.replace(RegExp('(//s|^)'+csName+'(//s|$)'),' '); //Use the regular to capture the name of the style to be deleted, and then replace it with a blank string, which is equivalent to deletion} deleteClass(odiv,div3); } </script> </head> <body> <div id="div1" class='div2'> Test</div> </body></html>The simple implementation of adding multiple classes to elements in JavaScript is the entire content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.