Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select first parent DIV using jQuery?

var classes = $(this).attr('class').split(' '); // this gets the current element classes  var classes = $(this).parent().attr('class').split(' '); // this gets the parent classes. 

The parent in the above situation is an ankor.

If I wanted to get the first parent DIV of $(this) what would the code look like?

var classes = $(this).div:parent().attr('class').split(' '); // just a quick try. 

* Basically I want to get the classes of the first parent DIV of $(this).

thx

like image 632
Adam Avatar asked Aug 17 '11 07:08

Adam


People also ask

How do I find a specific parent 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.

What does $( Div parent will select?

The :parent Selector page on jQuery says: Select all elements that have at least one child node (either an element or text). So $('div') would select all divs and $('div:parent') would select only those with children.

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.


2 Answers

Use .closest() to traverse up the DOM tree up to the specified selector.

var classes = $(this).parent().closest('div').attr('class').split(' '); // this gets the parent classes. 
like image 84
Shef Avatar answered Sep 21 '22 09:09

Shef


Use .closest(), which gets the first ancestor element that matches the given selector 'div':

var classes = $(this).closest('div').attr('class').split(' '); 

EDIT:

As @Shef noted, .closest() will return the current element if it happens to be a DIV also. To take that into account, use .parent() first:

var classes = $(this).parent().closest('div').attr('class').split(' '); 
like image 22
Tatu Ulmanen Avatar answered Sep 21 '22 09:09

Tatu Ulmanen