Mako
Mako

Reputation: 1515

Getting parent tr element from child element in jQuery

I have the following table structure in my code

<tr>
  <td>Text 1 </td>
  <td>Text 2 </td>
  <td> <span class="edit" onclick="EditAccountInfo(id1)" /> </td>
</tr>
<tr>
  <td>Text 1 </td>
  <td>Text 2 </td>
  <td> <span class="edit" onclick="EditAccountInfo(id2)" /> </td>
</tr>

On clicking the span in the <td>, I want to highlight the selected row (<tr>). I am using the following code in the javascript function

function EditAccountInfo(id)
{
  $(this).closest('tr').css("background-color", "red");
}

I am not getting any errors and $(this).closest('tr') returns a valid object, but the background color style is not getting applied to the <tr>.

What am i doing wrong?

Upvotes: 0

Views: 8089

Answers (3)

captbrogers
captbrogers

Reputation: 494

$('#my-table').on('click', '.edit', function () {
    $(this).closest('tr').css('backgroundColor','red');
});

Upvotes: 0

Joao Paulo
Joao Paulo

Reputation: 1103

Try

$(document).ready(function () {
    $('td').click(function(){
        $(this).parent().css("background","red");
    });
});

Upvotes: 0

Jason P
Jason P

Reputation: 27012

this is the window because you're using inline event handlers. I would recommend a more unobtrusive approach:

<span class="edit" data-account-id="id1" />

$(document).on('click', '.edit', function() {
    var $tr = $(this).closest('tr');
    var id = $(this).data('account-id');
    //...
});

Upvotes: 1

Related Questions