简体   繁体   中英

jQuery closest() getting above row with a certain class or id

The following is a simplified example to explain what I am trying to understand, namely how to get the first row above the current row that has a certain id:

<script>
$(document).ready(function(){
  $("#alphabet").closest("tr']").css({"color": "white", "background-color": "green"}); // finds the same row as expected
  $("#alphabet").closest("tr#number']").css({"color": "white", "background-color": "green"});  // Does NOT find anything
  $("#alphabet").closest("tr:has([class*='num'])").css({"color": "white", "background-color": "green"}); // Does NOT find anything

});
</script>
</head>

<body >body (great-great-grandparent)
  <table>
    <thead>
      <tr>
          <th>col 1</th>
          <th>col 2</th>
      </tr>
  </thead>
    <tbody>
      <tr id='number' class="num">
          <td>1</td>
          <td>2</td>
      </tr>
      <tr id='alphabet'>
          <td>a</td>
          <td>b</td>
      </tr>
    </tbody>
  </table>

</body>

I am intentionally avoiding the use of .next(), prev().

try:

$("#alphabet").siblings('#number').css(...)

Closest is for moving up the hierarchy, eg from td to tr, siblings for moving around same level.

Given a jQuery object that represents a set of DOM elements, the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements. The .parents() and .closest() methods are similar in that they both traverse up the DOM tree. The differences between the two, though subtle

May be best to use .parents() or .siblings() . .closest() will not be able to see the element as it will have already traverse to <tbody> in it's first step.

 $(function() { $("#alphabet").parent().find("#number").css({ "color": "white", "background-color": "green" }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <thead> <tr> <th>col 1</th> <th>col 2</th> </tr> </thead> <tbody> <tr id='number' class="num"> <td>1</td> <td>2</td> </tr> <tr id='alphabet'> <td>a</td> <td>b</td> </tr> </tbody> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM