Home  >  Article  >  Web Front-end  >  How to clear all child elements under an element in jquery

How to clear all child elements under an element in jquery

青灯夜游
青灯夜游Original
2022-04-28 18:32:566212browse

Clearing method: 1. Use children() to get all child elements under the specified element. The syntax "$("specified element").children()" will return an object containing all child elements; 2 . Use remove() to delete the obtained child element and all its internal contents. The syntax is "element object.remove()".

How to clear all child elements under an element in jquery

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

jquery method to clear all child elements under an element

Implementation method:

  • Use children () Get all sub-elements under the specified element

  • Use remove() to delete the obtained sub-elements

    The remove() method can remove the element and its Delete all content inside

Implementation example: Delete all sub-elements within the div

<!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:150px;background-color:yellow">
			这是一些文本。
			<p>这是div块中的一个段落,子元素。<span>这是一个span块,孙元素</span></p>
			<p>这是div块中的一个段落,子元素。</p>
			<span>这是一个span块,子元素</span>
		</div>
		<p>这是div块外部的一个段落。</p>
		<button>删除div内所有子元素</button>

	</body>
</html>

How to clear all child elements under an element in jquery

Note: The div also contains some text content, it is not a child element and therefore will not be deleted.

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

The above is the detailed content of How to clear all child elements under 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