Home > Web Front-end > JS Tutorial > body text

How to modify css class in js

青灯夜游
Release: 2023-01-07 11:41:41
Original
3389 people have browsed it

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>
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template