1

My sample HTML

<tr>
    <td>
        <div><span id="temp" />
        </div>
    </td>
</tr>
<tr>
    <td>
        <div><span id="temp" />
        </div>
    </td>
</tr>

From the Span tag how do i get the Table tr tag and set its background color ? Any easy methods rather than finding parent.parent?

And only the particular span tag TR should be changed not all the table TR ?

Thanks

6
  • 2
    $('#temp').parents('tr').css('background-color', 'red'); Commented Jun 25, 2013 at 14:51
  • @Chen Excellent and quick . Modified my question. i need only one TR to change not all the TR. is there a easy way out Commented Jun 25, 2013 at 14:56
  • @user2067567: See answer by pXL and comment. Commented Jun 25, 2013 at 14:56
  • Use .closest() instead of .parents(), will return only the closest tr. Commented Jun 25, 2013 at 14:59
  • Even that affects all TR Commented Jun 25, 2013 at 14:59

3 Answers 3

11

you can use .closest()

$('#temp').closest('tr').css('background-color', 'green');
Sign up to request clarification or add additional context in comments.

4 Comments

+1 as .parents() causes problems in nested tables, as it matches all <tr> parents and will return multiple. Whereas .closest() returns the closest ancestor that matches.
@pXL how do i make it affect only tat TR and not all TR
+1. I just read the docs for .closest() and .parents() and this seems to be faster
@user2067567, see this demo, when you click on tr, only that tr will change its bg color -----> jsfiddle.net/8NmSA
1

in jQuery:

$("#temp").parents("tr").css('background-color', 'green');              

Comments

1

Try .parents()

$('#temp').parents('tr').first().css({'background-color': '#fff'});

.first() exclude elements in cause of nested tables.

Or .closest()

$('#temp').closest('tr').css({'background-color': '#fff'});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.