parents([selector]) trong jQuery



Miêu tả

Phương thức parents([selector]) trong jQuery nhận một tập hợp các phần tử chứa tổ tiên (ancestor) của tập hợp các phần tử đã so khớp (ngoại trừ các phần tử root).

Cú pháp

Sau đây là cú pháp để sử dụng parents([selector]) trong jQuery:

selector.parents( [selector] )

Tham số

Chi tiết tham số được sử dụng trong phương thức parents([selector]) trong jQuery:

  • selector − Selector tùy ý để lọc các ancestor.

Quảng cáo

Ví dụ

Ví dụ đơn giản sau minh họa cách sử dụng của parents([selector]) trong jQuery. Bạn thử ví dụ mà không truyền bộ chọn phần tử cha như ".top".

<html>
   <head>
      <title>The jQuery Example</title>
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
	
      <script type="text/javascript" language="javascript">
         $(document).ready(function(){
            var parentEls = $("p").parents()
            .map(function () { 
               return this.tagName; 
            }).get().join(", ");
            $("b").append("<strong>" + parentEls + "</strong>");
         });
      </script>

   </head>
	
   <body>
	
      <scan>Top Element</scan>
      <div>
		
         <div class="top">Top division            
            <p class="first">First Sibling</p>
            <scan>Second sibling</scan>
            <p class="third">Third sibling</p>
         </div>
			
         <b>Parents of <p> elements are: </b>
      </div>
		
   </body>
	
</html>
Quảng cáo

Nó sẽ cho kết quả:

Các bài học jQuery khác tại VietJack:


truy_cap_dom_trong_jquery.jsp