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

How to modify css style through classes in js

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

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

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

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