jQuery parent() 方法



jQuery 中的 parent() 方法用於向上遍歷 DOM 樹,到達所選元素的父元素。它選擇並返回 DOM 層次結構中所選元素的直接父元素。

如果我們想一直向上遍歷 DOM 樹(返回祖父母、曾祖父母或祖先),我們需要使用 parents()parentsUntil() 方法。

語法

以下是 jQuery 中 parent() 方法的語法:

$(selector).parent(filter)

引數

此方法接受以下可選引數:

  • filter: 包含選擇器表示式的字串,用於根據特定條件篩選父元素。

示例 1

在以下示例中,我們使用 parent() 方法返回 <p> 元素的直接父元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $("button").click(function(){
      $("p").parent().css({"background-color": "lightblue"})
    })
  })
</script>
</head>
<body>
  <div style="border: 3px solid black; height: 30%; width: 0%;">
    <p style="border: 2px solid red; text-align: center; margin-top: 60px;">Click on the below button to find the parent element of <b>p</b> element</b>.</p>
  </div>
<button>Click here!</button>
</body>
</html>

當我們執行上述程式並點選按鈕時,它將選擇父元素 (div) 並將其背景顏色更改為淺藍色。

示例 2

在下面的示例中,我們選擇每個 <span> 元素的直接父元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $("button").click(function(){
      $("span").parent().css({"background-color": "lightblue"})
    })
  })
</script>
</head>
<body>
  <p>Paragraph element.</p>
  <p>Paragraph element.</p>
  <p>Paragraph element <span>Hello, I'am span element.</span></p>
  <p>Paragraph element <span>Hello, I'am span element.</span></p>
  <p>Paragraph element.</p>
<button>Click here!</button>
</body>
</html>

當我們執行上述程式並點選按鈕時,span 元素的直接父元素將被選中,並且它們的背景顏色將更改為淺藍色。

示例 3

在這裡,我們選擇每個 <span> 元素的所有直接父 (<div>) 元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function(){
    $("button").click(function(){
      $("span").parent("p.one").css({"background-color": "lightblue"})
    })
  })
</script>
</head>
<body>
  <p>Paragraph element.</p>
  <p>Paragraph element.</p>
  <p class="one">Paragraph element (with class "one") <span>Hello, I'am span element.</span></p>
  <p class="two">Paragraph element (with class "two") <span>Hello, I'am span element.</span></p>
  <p>Paragraph element.</p>
<button>Click here!</button>
</body>
</html>

執行上述程式後,span 元素的直接父元素將被選中,並且它們的背景顏色將更改為淺藍色。

jquery_ref_traversing.htm
廣告