Element-relative CSS selectors

452 views Asked by At

Is there a way to shorten these types of lines by using CSS selectors and jQuery?

$(element).parent('tr').parent('tbody').parent('table')

$(element).children('tbody').children('tr').children('td')

It is basically: "get me the direct parent/children if any"

I need 100% equal selectors.

UPDATE:

closest('table) does not work: can return the element itself AND may find not direct parents find('td') does not work: as I need only the direct children; there might be plenty of them in the subtree below

3

There are 3 answers

10
Arun P Johny On BEST ANSWER

You can use .closest() to find the first ancestor mathcing the given selector

element.parent('tr').parent('tbody').parent('table') -> $(element).parent('tr').closest('table')

In the below case use find() with child selector

element.children('tbody').children('tr').children('td') -> element.find('> tbody > tr > td')
0
Tushar On

You can use closest to get the closest ancestor:

element.closest('table') // element.parent('tr').parent('tbody').parent('table')

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

Docs: http://api.jquery.com/closest/

and find to search down the DOM tree:

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

element.find('td') // element.children('tbody').children('tr').children('td')

Docs: http://api.jquery.com/find/

0
kapantzak On

Use closest to move up to the closest matching element. Also, use find to search into the given element (note that find will get all the matching elements going down to all the existing DOM tree layers)

element.closest('table');
element.find('td');