Home  >  Article  >  Web Front-end  >  How to delete an element in jquery

How to delete an element in jquery

青灯夜游
青灯夜游Original
2022-04-22 15:09:5210983browse

Methods to delete elements: 1. Use remove() to delete the specified element and all the content inside it. The syntax is "$(selector).remove()"; 2. Use detach() to remove it. Except the selected element and all text and child nodes inside it, the syntax is "$(selector).detach()".

How to delete an element in jquery

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

Delete an element in jQuery

1. Use the remove() method

in jQuery , we can use the remove() method to delete an element and all its contents.

Syntax:

$(selector).remove()

Example: Use remove() to remove p element

<!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").remove();
				});
			});
		</script>
	</head>
	<body>

		<div>这是一个div段落。</div>
		<p>这是另一个p段落。</p>
		<button>移除P元素</button>

	</body>
</html>

How to delete an element in jquery

2. Use detach() Method

In jQuery, we can use the detach() method to remove selected elements, including all text and child nodes. However it will retain data and events.

This method keeps a copy of the removed elements, allowing them to be reinserted later.

Grammar:

$(selector).detach()

Example: Use detach() to remove the p element

<!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").detach();
				});
			});
		</script>
	</head>
	<body>
		<p>这是另一个p段落。</p>
		<div>这是一个div段落。</div>
		<button>移除P元素</button>

	</body>
</html>

How to delete an element in jquery

[Recommended learning: jQuery video Tutorialweb front-end video

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