Home  >  Article  >  Web Front-end  >  How to modify css class in js

How to modify css class in js

青灯夜游
青灯夜游Original
2021-07-01 17:23:023339browse

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")".

How to modify css class in js

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(&#39;myid&#39;);
x.className="otherstyle";
document.getElementById(&#39;div&#39;).innerHTML="Body CSS class名为:"+ x.className;
}
</script>
</body>
</html>

Rendering:

How to modify css class in js

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(&#39;myid&#39;);
x.setAttribute("class", "otherstyle");
document.getElementById(&#39;div&#39;).innerHTML="Body CSS class名为:"+ x.className;
}
</script>
</body>
</html>

Rendering:

How to modify css class in js

[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!

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