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

How to add a class to an element in jquery

青灯夜游
青灯夜游Original
2022-03-18 19:12:014606browse

Jquery method to add a class to an element: 1. Use the attr() method, syntax "$(selector).attr("class","class name")"; 2. Use the addClass() method, Syntax "$(selector).addClass("class name")".

How to add a class to an element in jquery

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

Add a class to the element in jquery

1. Use the attr() method

The attr() method sets or returns the attribute value of the selected element.

According to the different parameters of this method, its working method is also different.

<!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","intro");
				});
			});
		</script>
		<style>
			.intro {
				font-size: 150%;
				color: red;
			}
		</style>
	</head>
	<body>

		<h1>这是一个标题</h1>
		<p>这是一个段落。</p>
		<p>这是另一个段落。</p>
		<button>给第一个P元素添加一个类名</button>

	</body>
</html>

How to add a class to an element in jquery

2. Use the addClass() method

addClass() method to add one or more class names to the selected element .

This method does not remove the existing class attribute, but only adds one or more class names to the class attribute.

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

<!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").addClass("intro");
				});
			});
		</script>
		<style>
			.intro {
				font-size: 150%;
				color: pink;
			}
		</style>
	</head>
	<body>

		<h1>这是一个标题</h1>
		<p>这是一个段落。</p>
		<p>这是另一个段落。</p>
		<button>给第一个P元素添加一个类名</button>

	</body>
</html>

How to add a class to an element in jquery

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

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