jQuery中parent方法与parents方法

1、parent方法
得到一个唯一父元素的元素集合
2、parents方法
取得包含着所有祖先元素的元素集合
具体请看以下示例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="../js/jquery-3.3.1.js"></script>
	</head>
	<body>
		<form>
			<input/>
			<input type="radio" value="1" />男
			<input type="radio" value="2"/>女
			<input type="submit" value="提交" />
		</form>
		<script>
			var dom = $("[type='submit']").parent()[0];
			console.log(dom);
			$("[type='submit']").parents().each(function(){
				console.log(this);
			});
		</script>
	</body>
</html>

效果:
在这里插入图片描述
分析:
第一个parent方法得到的有< form>< /form>集合,因为其是唯一的匹配的集合。
第二个parents方法得到的有< form>< /from>、< body>< /body>、< html>< /html>,这是按照“由内至外”的顺序。

发布了54 篇原创文章 · 获赞 1 · 访问量 867

猜你喜欢

转载自blog.csdn.net/weixin_44764207/article/details/102990972
今日推荐