在jQuery中有两个可以获取父标签的方法parent()和parents(),二者的区别在于,parent()方法获取的父标签是距离调用者最近的父标签,而parents()方法获取的父标签是包含调用者的所有父标签组成的数组。
以下是代码示例:
首先用属性选择器选中form标签中type为submit的input标签,然后先调用parent方法,并将其jQuery对象转换为DOM对象再打印;
然后还是获取form标签中type为submit的input标签,然后调用parents方法,再使用each循环打印dom中所有的对象,运行结果如下:
<!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="password" />
<input type="radio" value="0"/>男<input type="radio" value="1"/>女
<input type="submit" value="提交"/>
</form>
<script>
var dom = $("input[type='submit']").parent()[0];
console.log(dom);
dom=$("input[type='submit']").parents().each(function(){
console.log(this);
})
</script>
</body>
</html>