Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find highest parent TD

I'm working on a code for a form contained within a table. I'm writing (with jQuery) a function to highlight the parent <td> of each <input> element. That part is simple - the code is just:

$('.myForm input').click(function(){
    $(this).parent().addClass('active');
    })

The more complicated part is that some text fields are inside of a second table nested within a <td> of the first table. It would look like:

<table>
    <tr>
        <td> <--cell I want to add the class to
            <table>
                <tr>
                    <td><input type='text'></td>
                </tr>
            </table>
        </td>
     </tr>
</table>

So my question is this: is there a way to use one jQuery statement to find the highest parent <td> of the <input> element? So in other words, can I combine:

$('.myForm input').click(function(){
    $(this).parent().addClass('active');
    })

and

$('.myForm input').click(function(){
    $(this).parent().parent().addClass('active');
    })

into one function?

like image 614
Zak Avatar asked Nov 16 '11 22:11

Zak


People also ask

How to parent element in jQuery?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.

Where can I find grandparents in jQuery?

jQuery parentsUntil() Method The parentsUntil() method returns all ancestor elements between the selector and stop. An ancestor is a parent, grandparent, great-grandparent, and so on.

How can get TD of TR in jQuery?

jQuery(". dname"). find("tr td:eq(1)"). val();


2 Answers

The best solution is to add a class to the table you actually want to target. This means that you could update the markup in future without necessarily breaking the JS, by doing something like $(this).closest('.targetElement').addClass('active').

If you can't do that, you can use parents('td').last(). This selects all td parent elements and then gets the last one.

$('.myForm input').click(function(){
    $(this).parents('td').last().addClass('active');
})

See the jQuery manual:

  • closest
  • parents
  • last
like image 118
lonesomeday Avatar answered Sep 19 '22 03:09

lonesomeday


Try doing this:

$('.myForm input').click(function(){
   $(this).parents('td').last().addClass('active');
})
like image 40
Rocket Hazmat Avatar answered Sep 18 '22 03:09

Rocket Hazmat