jQuery向父輩遍曆的方法

來源:互聯網
上載者:User

標籤:

 

通過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"元素之間的所有元素

 1 <!DOCTYPE html> 2 <html> 3 <head> 4  <meta charset="UTF-8"> 5  <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"> 6 </script> 7  <style> 8  .container 9  {10     float:left;11     margin-left:30px;12  }13 .container div14   {15     border:1px solid grey;16     margin:15px auto;17   }18 .ancestor1-1,.ancestor2-1,.ancestor3-1,.ancestor4-119 {20     width:150px;21     height:150px;22 }  23 .ancestor1-2,.ancestor2-2,.ancestor3-2,.ancestor4-224 {25     width:120px;26     height:120px;27 }28 .ancestor1-3,.ancestor2-3,.ancestor3-3,.ancestor4-329 {30     width:90px;31     height:90px;32 }33 .now1,.now2,.now3,.now434 {35     width:60px;36     height:60px;37 }38  </style>39  <script>40 $(document).ready(function(){41 $(".now1").parent().css("border-color","red");42 $(".now2").parents().css("border-color","red");43 $(".now3").parents(".ancestor3-2").css("border-color","red");44 $(".now4").parentsUntil(".ancestor4-1").css("border-color","red");45 }46 );47  </script>48 </head>49 <body>50 <div>51     <div class="container">52         <div class="ancestor1-1"><div class="ancestor1-2"><div class="ancestor1-3"><div class="now1">給定元素</div></div></div></div>53     </div>54     <div class="container">55         <div class="ancestor2-1"><div class="ancestor2-2"><div class="ancestor2-3"><div class="now2">給定元素</div></div></div></div>56     </div>57     <div class="container">58         <div class="ancestor3-1"><div class="ancestor3-2"><div class="ancestor3-3"><div class="now3">給定元素</div></div></div></div>59     </div>60     <div class="container">61         <div class="ancestor4-1"><div class="ancestor4-2"><div class="ancestor4-3"><div class="now4">給定元素</div></div></div></div>62     </div>63 </div>64 </body>65 </html>

 

:

 

 分類: JavaScript

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.