Home >Web Front-end >Front-end Q&A >How to delete the element itself in jquery

How to delete the element itself in jquery

青灯夜游
青灯夜游Original
2022-04-27 19:07:422206browse

Deletion method: 1. Use remove() to delete the element and all its contents. The syntax is "specified element.remove();"; 2. Use children() and unwrap() to delete the element, but The reserved child nodes inside, the syntax is "specify element.children().unwrap();".

How to delete the element itself in jquery

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

jquery deletion of the element itself can be divided into two situations:

  • Delete the element itself and the content inside it (text and child nodes)

  • Only delete the element itself and keep the child nodes

Case 1. Use the remove() method

Use the remove() method to delete an element and all its contents.

<!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(){
				$("div").remove();
			  });
			});
		</script>
		<style type="text/css">
			div {
				background-color: yellow;
			}
		</style>
	</head>
	<body>

		<div>
			<p>这是 div 元素中的段落。</p>
			<p>这是 div 元素中的段落。</p>
			<p>这是 div 元素中的段落。</p>
		</div>
		<button>删除div元素</button>

	</body>
</html>

How to delete the element itself in jquery

Case 2: Using the children() unwrap() method

  • children() method returns Returns all direct children of the selected element.

  • The unwrap() method removes the parent element of the selected 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(){
				$("div").children().unwrap();
			  });
			});
		</script>
		<style type="text/css">
			div {
				background-color: yellow;
			}
		</style>
	</head>
	<body>

		<div>
			<p>这是 div 元素中的段落。</p>
			<p>这是 div 元素中的段落。</p>
			<p>这是 div 元素中的段落。</p>
		</div>
		<button>删除div元素</button>

	</body>
</html>

How to delete the element itself in jquery

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

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