How to delete all child elements in div with jquery

青灯夜游
Release: 2022-04-21 19:09:06
Original
7471 people have browsed it

Deletion method: 1. Use empty(), the syntax "$("div").empty();" to delete all child nodes and content; 2. Use children() and remove(), The syntax "$("div").children().remove();" only deletes the child elements but not the content.

How to delete all child elements in div with jquery

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

jquery deletes all child elements within the div

Method 1: Use empty()

The empty() method removes all child nodes and content of the selected element. This method does not remove the element itself, or its attributes.

The empty() method is used to "empty" descendant elements.

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

		<div style="height:100px;background-color:yellow">
			这是一些文本。
			<p>这是div块中的一个段落。</p>
		</div>
		<p>这是div块外部的一个段落。</p>
		<button>移除div块中的内容</button>

	</body>
</html>
Copy after login

How to delete all child elements in div with jquery

Method 2: Use children() and remove()

remove( ) method can remove elements and their internal Deletion of all content

Therefore, you need to first use the children() method to obtain all child elements of the div element, and then use the remove() method to delete the obtained child elements.

But this method will not delete the text content of the div element itself.

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

		<div style="height:100px;background-color:yellow">
			这是一些文本。
			<p>这是div块中的一个段落,子元素。</p>
			<p>这是div块中的一个段落,子元素。</p>
		</div>
		<p>这是div块外部的一个段落。</p>
		<button>移除div块中的内容</button>

	</body>
</html>
Copy after login

How to delete all child elements in div with jquery

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

The above is the detailed content of How to delete all child elements in div with 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!