Home  >  Article  >  Web Front-end  >  How to use jquery addclass()

How to use jquery addclass()

青灯夜游
青灯夜游Original
2022-03-01 16:05:403047browse

In jquery, the addclass() method is used to add one or more classes to the selected element. The syntax is "$(selector).addClass("class name")"; if you need to add multiple classes , you need to use spaces to separate class names.

How to use jquery addclass()

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

In jquery, the addclass() method is used to add 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.

Tip: If you need to add multiple classes, please use spaces to separate class names.

Syntax

$(selector).addClass(class)

Also use functions to add classes to selected elements

$(selector).addClass(function(index,oldclass))

How to use jquery addclass()

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").addClass("intro");
				});
			});
		</script>
		<style type="text/css">
			.intro {
				font-size: 120%;
				color: red;
			}
		</style>

	</head>

	<body>
		<h1>这是一个大标题</h1>
		<p>这是一个段落。</p>
		<p>这是另一个段落。</p>
		<button>向第一个 p 元素添加一个类</button>
	</body>

</html>

How to use jquery addclass()

Add two classes to the 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").addClass("intro note");
				});
			});
		</script>
		<style type="text/css">
			.intro {
				font-size: 120%;
				color: blue;
			}

			.note {
				background-color: yellow;
			}
		</style>

	</head>

	<body>
		<h1>这是一个大标题</h1>
		<p>这是一个段落。</p>
		<p>这是另一个段落。</p>
		<button>向第一个 p 元素添加一个类</button>
	</body>

</html>

How to use jquery addclass()

[Recommended learning: jQuery video tutorial, web front-end

The above is the detailed content of How to use jquery addclass(). 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