parent([selector]) trong jQuery



Miêu tả

Phương thức parent([selector]) trong jQuery nhận phần tử cha trực tiếp của một phần tử. Nếu được gọi trên một tập hợp các phần tử, phương thức parent trả về một tập hợp các phần tử cha trực tiếp duy nhất.

Cú pháp

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

selector.parent( [selector] )

Tham số

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

  • selector − Đây là Selector tùy ý để lọc phần tử cha.

Quảng cáo

Ví dụ

Ví dụ đơn giản sau minh họa cách sử dụng của parent([selector]) trong jQuery.

<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(){
            $("p").parent().addClass('hilight');
         });
      </script>
		
      <style>
         .hilight { background:yellow; }
      </style>

   </head>
	
   <body>
	
      <scan>Top Element</scan>
		
      <div>
         <div>sibling<div>child</div></div>
         <p>sibling</p>
         <scan>sibling</scan>
      </div>
		
   </body>
	
</html>
Quảng cáo

Nó sẽ cho kết quả:

<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(){
            $("p").parent().addClass('hilight');
         });
      </script>
		
      <style>
         .hilight { background:yellow; }
      </style>

   </head>
	
   <body>
      <scan>Top Element</scan>
		
      <div class="hilight">
         <div>sibling<div>child</div></div>
         <p>sibling</p>
         <scan>sibling</scan>
      <div>
   </body>
	
</html>

Nó sẽ cho kết quả:

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


truy_cap_dom_trong_jquery.jsp