Home  >  Article  >  Web Front-end  >  How to add elements to body in jquery

How to add elements to body in jquery

青灯夜游
青灯夜游Original
2022-04-22 11:13:595469browse

Methods to add elements: 1. Use append(), the syntax "$("body").append(new element)" to add elements to the end of the body; 2. Use prepend() , the syntax "$("body").prepend(new element)" can add elements to the beginning of the body.

How to add elements to body in jquery

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

Adding elements to the body means adding sub-elements to the body. The following article will introduce to you two methods of adding child elements to the body using jquery.

Method 1: Use append()

Use prepend() method to insert content (element or text) to the "beginning" inside the body element

Syntax:

$("body").append(新元素)

Example:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script>
			$(function() {
				$("button").click(function() {
					var newp = "<p>一个新段落</p>";
					$("body").append(newp);
				})
			})
		</script>
	</head>
	<body style="background-color: #FF0000;">
		<button>(body元素)在body中增加元素</button>
	</body>
</html>

How to add elements to body in jquery

Method 2: Use prepend()

Use the prepend() method to insert content to the "beginning" inside the selected element.

Grammar:

$("body").prepend(新元素)

Example:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script>
			$(function() {
				$("button").click(function() {
					var newp = "<p>一个新段落</p>";
					$("body").prepend(newp);
				})
			})
		</script>
	</head>
	<body style="background-color: #FF0000;">
		<button>(body元素)在body中增加元素</button>
	</body>
</html>

How to add elements to body in jquery

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

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