jQuery向父輩遍曆的簡單方法,jquery父輩

來源:互聯網
上載者:User

jQuery向父輩遍曆的簡單方法,jquery父輩

通過DOM樹可以可容易的訪問到html文檔中的所有元素

例如向上訪問父輩的元素有以下方法

1.parent()方法可以得到所定元素的直接父元素

$("span").parent();得到<span>元素的直接父元素

2.parents()方法得到給定元素的所有父元素

$("span").parents();得到<span>元素的所有父元素

$("span").panents(".text");得到<span>元素的父元素中class="text"的元素

3.parentsUntil()方法得到兩個給定元素之間的元素

$("span").parentsUntil(".text");得到<span>元素與class="text"元素之間的所有元素

<!DOCTYPE html><html><head> <meta charset="UTF-8"> <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script> <style> .container {  float:left;  margin-left:30px; }.container div {  border:1px solid grey;  margin:15px auto; }.ancestor1-1,.ancestor2-1,.ancestor3-1,.ancestor4-1{  width:150px;  height:150px;} .ancestor1-2,.ancestor2-2,.ancestor3-2,.ancestor4-2{  width:120px;  height:120px;}.ancestor1-3,.ancestor2-3,.ancestor3-3,.ancestor4-3{  width:90px;  height:90px;}.now1,.now2,.now3,.now4{  width:60px;  height:60px;} </style> <script>$(document).ready(function(){$(".now1").parent().css("border-color","red");$(".now2").parents().css("border-color","red");$(".now3").parents(".ancestor3-2").css("border-color","red");$(".now4").parentsUntil(".ancestor4-1").css("border-color","red");}); </script></head><body><div>  <div class="container">    <div class="ancestor1-1"><div class="ancestor1-2"><div class="ancestor1-3"><div class="now1">給定元素</div></div></div></div>  </div>  <div class="container">    <div class="ancestor2-1"><div class="ancestor2-2"><div class="ancestor2-3"><div class="now2">給定元素</div></div></div></div>  </div>  <div class="container">    <div class="ancestor3-1"><div class="ancestor3-2"><div class="ancestor3-3"><div class="now3">給定元素</div></div></div></div>  </div>  <div class="container">    <div class="ancestor4-1"><div class="ancestor4-2"><div class="ancestor4-3"><div class="now4">給定元素</div></div></div></div>  </div></div></body></html>

以上這篇jQuery向父輩遍曆的簡單方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.