Home  >  Article  >  Web Front-end  >  How to modify the class name of dom element in jquery

How to modify the class name of dom element in jquery

青灯夜游
青灯夜游Original
2022-05-30 14:32:281629browse

Two modification methods: 1. Use attr() to modify the value of the class attribute, the syntax is "dom element object.attr("class","new class name")"; 2. After removing the old class To add a new class, the syntax is "dom element object.removeClass("old class name").addClass("new class name")".

How to modify the class name of dom element in jquery

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

jquery method of modifying the class name of a dom element

Method 1: Directly use attr() to modify the value of the class attribute

attr() method can set the attribute value of the selected element.

<!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:first").attr("class","intro2");
				});
			});
			</script>
		<style type="text/css">
			.intro1 {
				font-size: 120%;
				color: red;
			}
			.intro2 {
				font-size: 120%;
				color: green;
			}
		</style>
	</head>
	<body>

		<h1>这是一个段落标题</h1>
		<p class="intro1">这是一个段落</p>
		<p> 这是另外一个段落</p>
		<button>修改p元素的 "intro1" 类</button>

	</body>
</html>

How to modify the class name of dom element in jquery

Method 2: Use removeClass() and addClass()

  • Use removeClass() first Remove the specified class

  • and then use addClass() to add a new 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:first").removeClass("intro1").addClass("intro2");
				});
			});
			</script>
		<style type="text/css">
			.intro1 {
				font-size: 120%;
				color: red;
			}
			.intro2 {
				font-size: 120%;
				color: green;
			}
		</style>
	</head>
	<body>

		<h1>这是一个段落标题</h1>
		<p class="intro1">这是一个段落</p>
		<p> 这是另外一个段落</p>
		<button>修改p元素的 "intro1" 类</button>

	</body>
</html>

How to modify the class name of dom element in jquery

[Recommended learning: jQuery video tutorialweb front-end video

The above is the detailed content of How to modify the class name of dom element 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
Previous article:Is jquery based on js?Next article:Is jquery based on js?