遍历Dom--祖先

向上遍历 DOM 树:

  • parent() 最近单个
  • parentsUntil() 区间
  • parents() 所有(间隔单个)

1、parent()

返回被选元素的直接父元素

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.ancestors *
{ 
	display: block;
	border: 2px solid lightgrey;
	color: lightgrey;
	padding: 5px;
	margin: 15px;
}
</style>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("span").parent().css({"color":"red","border":"2px solid red"});
});
</script>
</head>
<body>

<div class="ancestors">
  <div style="width:500px;">div (曾祖父元素)
    <ul>ul (祖父元素)  
      <li>li (父元素)
        <span>span</span>
      </li>
    </ul>   
  </div>

  <div style="width:500px;">div (祖父元素)   
    <p>p (父元素)
        <span>span</span>
      </p> 
  </div>
</div>

</body>
</html>

2、parentsUntil()

开区间筛选:

3、parents()

返回被选元素的所有祖先元素,它一路向上直到文档的根元素 (<html>)。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.ancestors *
{ 
	display: block;
	border: 2px solid lightgrey;
	color: lightgrey;
	padding: 5px;
	margin: 15px;
}
</style>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("span").parents().css({"color":"red","border":"2px solid red"});
});
</script>
</head>

<body class="ancestors">body (曾曾祖父元素)
  <div style="width:500px;">div (曾祖父元素)
    <ul>ul (祖父元素)  
      <li>li (父元素)
        <span>span</span>
      </li>
    </ul>   
  </div>
</body>

</html>

祖先元素的筛选:

 

发布了252 篇原创文章 · 获赞 5 · 访问量 7817

猜你喜欢

转载自blog.csdn.net/qq_32603969/article/details/103886475