js教程_jquery怎么判断指定子元素是否存在

 所属分类:web前端开发

 浏览:205次-  评论: 0次-  更新时间:2022-06-24
描述:更多教程资料进入js教程获得。 判断方法:1、使用“$("父元素").has("子元素").length”语句,如果返回值为1,则指定子元素存在;2、使用“...
更多教程资料进入js教程获得。

判断方法:1、使用“$("父元素").has("子元素").length”语句,如果返回值为1,则指定子元素存在;2、使用“$("父元素").children("子元素").length”语句,如果返回值大于等于1,则指定子元素存在。

本教程操作环境:windows7系统、jquery1.10.2版本、Dell G3电脑。

jquery判断指定子元素是否存在

方法1:利用has() 方法

has() 将匹配元素集合缩减为拥有匹配指定选择器或 DOM 元素的后代的子集。

<!DOCTYPE html>
<html>
	<head>
		<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function() {
				$("button").click(function() {
					if ($("div").has("span").length) {
						console.log("指定子元素存在")
					} else {
						console.log("指定子元素不存在")
					}
				});
			});
		</script>
	</head>

	<body>
		<div style="border: 1px solid red;">
			<p>子元素1</p>
			<span>子元素2</span>
		</div><br>
		<button>指定子元素span是否存在</button>
	</body>
</html>

1.gif

方法2:使用children()

children() 方法返回返回被选元素的所有直接子元素。

<!DOCTYPE html>
<html>
	<head>
		<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function() {
				$("button").click(function() {
					if ($("div").children("p").length) {
						console.log("指定子元素存在");
						console.log($("div").children("p").length);
					} else {
						console.log("指定子元素不存在");
						console.log($("div").children("p").length);
					}
				});
			});
		</script>
	</head>

	<body>
		<div style="border: 1px solid red;">
			<p>子元素1</p>
			<span>子元素2</span>
			<span>子元素2</span>
			<p>子元素3</p>
			<p>子元素4</p>
		</div><br>
		<button>指定子元素是否存在</button>
	</body>
</html>

2.gif

【推荐学习:jQuery视频教程、web前端】

以上就是jquery怎么判断指定子元素是否存在的详细内容,更多请关注zzsucai.com其它相关文章!

 标签:
积分说明:注册即送10金币,每日签到可获得更多金币,成为VIP会员可免金币下载! 充值积分充值会员更多说明»

讨论这个素材(0)回答他人问题或分享使用心得奖励金币

〒_〒 居然一个评论都没有……

表情  文明上网,理性发言!