Home > Web Front-end > Front-end Q&A > How to add id to element in jquery

How to add id to element in jquery

青灯夜游
Release: 2022-04-21 16:23:26
Original
6112 people have browsed it

In jquery, you can use the attr() method to add an id to an element; this method can add specified attributes to the element and set the specified attribute value. You only need to set the value of its first parameter to " id", the second parameter can be set to the specified id value, the syntax is "specified element object.attr("id","specified id value")".

How to add id to element in jquery

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

In jquery, you can use the attr() method to add an id to an element.

attr() method can add specified attributes to elements and set specified attribute values.

This method accepts two parameters:

$(selector).attr(attribute,value)
Copy after login
Specifies the name of the attribute. Specifies the value of the attribute.
ParametersDescription
##attribute
value
If you want to use the attr() method to add an id to an element, you only need to set the first parameter

attributes of the method to id, the second parameter value can be set to the specified id value.

Example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<style>
			#div{
				background-color: #FF0000;
				padding: 10px;
				margin: 10px;
			}
		</style>

		<script>
			$(document).ready(function() {
				$("button").on("click", function() {
					$("div").attr("id","div");
				});
			});
		</script>
	</head>

	<body class="ancestors">
		<div>这是一段测试文本</div>
		<button>给div元素增加id</button>
	</body>

</html>
Copy after login

How to add id to element in jquery

It can be seen that in the above example, the attr() method is used to add the id to the div element and pass The id selector adds styles to div elements.

[Recommended learning:

jQuery video tutorial, web front-end video]

The above is the detailed content of How to add id to element in jquery. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template