Skip to content

jQuery DOM Traversal - 父層

選取父層元素的方法。

parent()

取得當前元素的父層元素,可用選取器進行篩選。

範例

html
<ul>
  <li>List Item 1</li>
  <li>List Item 2</li>
  <li id="Item">List Item 3</li>
  <li>List Item 4</li>
  <li>List Item 5</li>
</ul>
js
$('#Item').parent().css('background-color', 'pink');

parents()

取得當前元素的所有父層元素,可用選取器進行篩選。

範例

html
<html>
  ...
  <body>
    <div>
      <section>
        <ul>
          <li>List Item 1</li>
          <li>List Item 2</li>
          <li id="Item">List Item 3</li>
          <li>List Item 4</li>
          <li>List Item 5</li>
        </ul>
      </section>
      ...
    </div>
  </body>
</html>
js
$('#Item').parents().css('background-color', 'pink');