Home  >  Article  >  Web Front-end  >  How to modify css style through classes in js

How to modify css style through classes in js

青灯夜游
青灯夜游Original
2021-07-22 16:07:354538browse

In JavaScript, you can use the setAttribute() method to modify the css style through classes. You only need to modify the "class" attribute value of the specified element. The syntax "element object.setAttribute("class", "New Class name ");".

How to modify css style through classes in js

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

In JavaScript, you can use the setAttribute() method to modify css styles through classes.

Let’s take a closer look through the code example:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <style>
			.style1{
				height: 50px;
				border: 1px solid red;
			}
			.style2{
				border: 3px dashed #AFEEEE;
				padding: 10px;
			}
		</style>
    </head>
    <body>
        <div id="style" class="style1">测试文本</div><br />
		<input type="button" value="更改类名" onclick="changeStyle()" />
    </body>
	<script>
		function changeStyle() {
		  var obj = document.getElementById("style");
		  obj.setAttribute("class", "style2");
		}
	</script>
</html>

Rendering:

How to modify css style through classes in js

Description:

The setAttribute() method adds the specified attribute and assigns it the specified value.

Only sets/changes the value if this specified property already exists.

Syntax

element.setAttribute(attributename,attributevalue)
Parameters Type Description
attributename String Required. The name of the attribute you wish to add.
attributevalue String Required. The attribute value you wish to add.

(Learning video sharing: css video tutorial)

The above is the detailed content of How to modify css style through classes in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn