Home  >  Article  >  Web Front-end  >  How to add a class in jquery

How to add a class in jquery

青灯夜游
青灯夜游Original
2022-05-18 19:50:182644browse

Two methods: 1. Use attr(), just add a value to the class attribute, the syntax is "element object.attr("class","class name");". 2. Use addClass() to add one or more classes. The syntax is "element object.addClass("class name")". If you add multiple classes, separate the class names with spaces.

How to add a class in jquery

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

Two ways to add a class in jquery

1. Use attr()

attr () can set the attribute value of the selected element, and add the class when the attribute is "class".

This method is used to add a new class when there is no class before.

Example: Add a class to the first p element

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function() {
				$("button").click(function() {
					$("p:first").attr("class","intro");
				});
			});
		</script>
		<style type="text/css">
			.intro {
				font-size: 120%;
				color: red;
			}
		</style>
	</head>

	<body>
		<h1>This is a heading</h1>
		<p>This is a paragraph.</p>
		<p>This is another paragraph.</p>
		<button>向第一个 p 元素添加一个类</button>
	</body>
</html>

How to add a class in jquery

##2. Use addClass()

addClass() method adds one or more classes to the selected element.

This method does not remove the existing class attribute, but only adds one or more class attributes. If you need to add multiple classes, separate the class names with spaces.

Example: Add a class to the second p element


<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function() {
				$("button").click(function() {
					$("p:nth-child(3)").addClass("intro");
				});
			});
		</script>
		<style type="text/css">
			.intro {
				font-size: 120%;
				color: red;
			}
		</style>
	</head>

	<body>
		<h1>一个大标题</h1>
		<p>第一个段落</p>
		<p>第二个段落</p>
		<p>第三个段落</p>
		<button>向第二个 p 元素添加一个类</button>
	</body>
</html>

How to add a class in jquery

[Recommended learning:

jQuery video tutorial, web front-end video

The above is the detailed content of How to add a class 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