Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Using Closest("element.class")

I am trying to find the closest tr that also matches a specific class name. The selector returns no matches. What am I not understanding?

For example:

<table>
<tbody class="category" id="cat-1">
<tr class="category-head">
  <th>Category 1</th>
</tr>
  <tr class="category-item">
    <th>Item 1</th>
  </tr>
  <tr>
    <td>This is a description of category item 1</td>
  </tr>
  <tr>
    <td><input type="text" name="c1_i1_input" id="c1_i1_input" class="category-item-input" /></td>
  </tr>
   <tr class="category-item">
    <th>Item 2</th>
  </tr>
  <tr>
    <td>This is a description of category item 2</td>
  </tr>
  <tr>
    <td><input type="text" name="c1_i2_input" id="c1_i2_input" class="category-item-input" /></td>
  </tr>
  </tbody>
</table>

<script type="text/javascript">
    $(document).ready(function () {
        $(".category-item-input").change(function () {
           //this works, returning the closest tr
            alert($(this).closest("tr").html());

            //this returns null?
            alert($(this).closest("tr.category-item").html());
        });

    });</script>
like image 502
Rokal Avatar asked Jun 04 '26 10:06

Rokal


1 Answers

Closest finds the closest ancestor element, not the nearest in the DOM. In your case the tr containing the input does not have the class and so the selector fails. You probably want to find the closest tr, then find the preceding previous sibling of that tr with the class.

$(this).closest('tr').prevAll('tr.category-item:last');
like image 122
tvanfosson Avatar answered Jun 06 '26 01:06

tvanfosson