JS method to modify css class: 1. Use the className attribute, the syntax "element object.className="css class name""; 2. Use the setAttribute() method, the syntax "element object.setAttribute("class ", "css class name")".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Method 1: Use the className attribute
The className attribute sets or returns the class attribute of the element.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style type="text/css"> .mystyle{ background-color: palegoldenrod; } .otherstyle{ background-color: palevioletred; } </style> </head> <body id="myid" class="mystyle"> <input type="button" value="更改类名" onclick="changeClass()"/><br /><br /> <div id="div">Body CSS class名为:mystyle</div> <script> function changeClass(){ var x=document.getElementById('myid'); x.className="otherstyle"; document.getElementById('div').innerHTML="Body CSS class名为:"+ x.className; } </script> </body> </html>
Rendering:
Method 2: Use setAttribute() method
setAttribute( ) method adds the specified attribute and assigns it the specified value.
Only sets/changes the value if this specified property already exists.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style type="text/css"> .mystyle{ background-color: palegoldenrod; } .otherstyle{ background-color: palevioletred; } </style> </head> <body id="myid" class="mystyle"> <input type="button" value="更改类名" onclick="changeClass()"/><br /><br /> <div id="div">Body CSS class名为:mystyle</div> <script> function changeClass(){ var x=document.getElementById('myid'); x.setAttribute("class", "otherstyle"); document.getElementById('div').innerHTML="Body CSS class名为:"+ x.className; } </script> </body> </html>
Rendering:
[Related recommendations: javascript learning tutorial]
The above is the detailed content of How to modify css class in js. For more information, please follow other related articles on the PHP Chinese website!