EarlyCoder
EarlyCoder

Reputation: 1313

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().

Upvotes: 0

Views: 473

Answers (2)

Twisty
Twisty

Reputation: 30893

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>

Upvotes: 1

corolla
corolla

Reputation: 5656

try:

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

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

Upvotes: 2

Related Questions