Home  >  Article  >  Web Front-end  >  How to replace class style in jquery

How to replace class style in jquery

青灯夜游
青灯夜游Original
2021-11-22 11:18:072821browse

Replacement method: 1. Use the removeClass() method to remove the old class style, and the addClass() method to add a new class style; 2. Use the attr() method to modify the class attribute and directly replace it with the new one. The class class is enough, the syntax is "$(element).attr("class","new class name")".

How to replace class style in jquery

The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.

jquery replacement class style

Method 1: Use removeClass() and addClass() methods

Use the removeClass() method to remove the old class style, and use the addClass() method to add a new class style

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script>
			$(document).ready(function(){
			  $("button").click(function(){
				$("p").removeClass("old-class").addClass("new-class") ;
			  });
			});
		</script>
		<style type="text/css">
			.old-class{
				border: 1px solid red; 
				background-color: #FFC0CB;
			}
			.new-class{
				border: 2px solid green; 
				background-color: #55aa7f;
				color: white;
			}
		</style>
	</head>
	<body>
		<p class="old-class">hello,测试文字</p>
		<button>替换类样式</button>
	</body>
</html>

How to replace class style in jquery

Method 2: Use attr()

Use the attr() method to modify the class attribute and replace it directly with the new class class

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script>
			$(document).ready(function(){
			  $("button").click(function(){
				$("p").attr("class","new-class");
			  });
			});
		</script>
		<style type="text/css">
			.old-class{
				border: 1px solid red; 
				background-color: #FFC0CB;
			}
			.new-class{
				border: 2px solid green; 
				background-color: #55aa7f;
				color: white;
			}
		</style>
	</head>
	<body>
		<p class="old-class">hello,测试文字</p>
		<button>替换类样式</button>
	</body>
</html>

How to replace class style in jquery

Recommended related video tutorials: jQuery Tutorial(Video)

The above is the detailed content of How to replace class style in jquery. 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