How to dynamically change CSS classes (style sheets) with JavaScript? To change a class name in JavaScript, you need to change the element's className attribute. This article will introduce the code to dynamically change CSS (style sheet) classes using JavaScript.
Let’s look directly at an example
Create the following HTML file.
JavaScriptChangeCssClass.html
<!DOCTYPE html><html><head> <meta charset="utf-8" /> <title></title> <script type="text/javascript"> function buttonClick() { target = document.getElementById("important"); if (target != null) { target.className = "importantText"; } } </script> <link rel="stylesheet" type="text/css" href="JavaScriptChangeCssClass.css"/> </head> <body> <p>这篇文章是很<span id="important">重要</span>的,需要特别注意。</p> <input id="Button1" type="button" value="button" onclick="buttonClick();"/> </body> </html>
JavaScriptChangeCssClass.css
.importantText{ font-weight:700; color:#FF0000; }
Description:
Click the button and the following code part will be executed
function buttonClick() { target = document.getElementById("important"); if (target != null) { target.className = "importantText"; } }
target = document.getElementById("important");
Therefore, the ID gets the important element. In this case, you can get the element with "important".
if (target != null) { target.className = "importantText"; }
If the element can be obtained, it is a non-null value, so the inner part of the if statement is executed. You can set the class of an element by assigning the className attribute. In this example, "importantText" is set to the class name.
According to this processing
<span id="important" class="importantText">重要</span>
changed the status.
Running results
Use a web browser to display the above HTML file. The effect shown below will be displayed.
Click the "button" button, the following effect will be displayed, "Important" will become a red font
The above is the entire content of this article. For more related exciting content, you can go to the JavaScript Video Tutorial column on the php Chinese website for further learning! ! !
The above is the detailed content of How to dynamically change a CSS stylesheet with JavaScript. For more information, please follow other related articles on the PHP Chinese website!