Home  >  Article  >  Web Front-end  >  How to determine whether the element content is empty in jquery

How to determine whether the element content is empty in jquery

青灯夜游
青灯夜游Original
2021-01-06 17:02:304219browse

Method: 1. Use html() to get the element content, and then use if to determine whether it is empty. The syntax is "if($(selector).html()){//not empty}". 2. Use the ":empty" selector to judge, the syntax is "if($(selector).is(":empty"))".

How to determine whether the element content is empty in jquery

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

Recommended tutorial: jQuery tutorial

jquery method to determine whether the element content is empty

1. Use html() Method to obtain the element content, and then use if to judge

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
	</head>

	<body>
		<p>默认文本。测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!</p>
		<script type="text/javascript">
			if($(&#39;p&#39;).html()) {
				alert(&#39;元素内容不为空&#39;)
			}else{
				alert(&#39;元素内容为空&#39;)
			}
		</script>
	</body>

</html>

2. Use the :empty pseudo-class to judge

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
	</head>

	<body>
		<p>默认文本。测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!测试文本!</p>
		<script type="text/javascript">
			if($(&#39;p&#39;).is(":empty")) {
				alert(&#39;元素内容为空&#39;)
			}else{
				alert(&#39;元素内容不为空&#39;)
			}
		</script>
	</body>

</html>

Rendering:

How to determine whether the element content is empty in jquery

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of How to determine whether the element content is empty 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