Home  >  Article  >  Web Front-end  >  How to modify the attribute value of div in jquery

How to modify the attribute value of div in jquery

青灯夜游
青灯夜游Original
2022-06-10 15:40:372995browse

Two methods to modify the attribute value: 1. Use attr() to modify the attribute value, the syntax is "$("div").attr("Attribute name", "New attribute value");" or " $("div").attr({Attribute 1: "New Value", Attribute 2: "New Value"....});". 2. Use prop() to modify the attribute value, the syntax is "$("div").prop("property name","new value");" or "$("div").prop({property 1:"new Value",Attribute2:"New value"...});".

How to modify the attribute value of div in jquery

The operating environment of this tutorial: windows7 system, jquery3.6.0 version, Dell G3 computer.

Two methods for jquery to modify the attribute value of a div

Method 1: Use attr() to modify the attribute value

Modify syntax:

//单个属性
$("div").attr("属性名","新属性值");

//多个个属性
$("div").attr({属性1:"新值",属性2:"新值"....});

Example: Modify the value of the style attribute

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<script src="./js/jquery-3.6.0.min.js"></script>
		<script>
		$(document).ready(function() {
			$("button").click(function() {
				$("div").attr("style","height:100px;background-color: #AFEEEE;");
			});
		});
		</script>
	</head>
	<body>

		<div style="height: 150px;border: 1px solid red;"></div>
		<br>
		<button>修改div的属性值</button>
	</body>
</html>

How to modify the attribute value of div in jquery

Method 2: Use prop( )Modify attribute value

Modify syntax:

//单个属性
$("div").prop("属性名","新值");
//多个个属性
$("div").prop({属性1:"新值",属性2:"新值"....});

Example: Modify class attribute

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<script src="./js/jquery-3.6.0.min.js"></script>
		<script>
		$(document).ready(function() {
			$("button").click(function() {
				$("div").attr("class","box2");
			});
		});
		</script>
		<style>
			.box1{
				height: 150px;
				background-color: #AFEEEE;
			}
			.box2{
				height: 100px;
				background-color: red;
			}
		</style>
	</head>
	<body>

		<div class="box1"></div>
		<br>
		<button>修改div的属性值</button>
	</body>
</html>

How to modify the attribute value of div in jquery

[Recommended learning :jQuery video tutorialweb front-end video

The above is the detailed content of How to modify the attribute value of div 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