How to select the 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 ankor.

If I wanted to get the first parent DIV from $ (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 from $ (this).

THX

+80
javascript jquery css-selectors
Aug 17 '11 at 7:27
source share
4 answers

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

 var classes = $(this).parent().closest('div').attr('class').split(' '); // this gets the parent classes. 
+128
Aug 17 2018-11-11T00:
source share

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

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

EDIT:

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

 var classes = $(this).parent().closest('div').attr('class').split(' '); 
+36
Aug 17 '11 at 7:30
source share

This gets the parent if it is a div. Then he gets a class.

 var div = $(this).parent("div"); var _class = div.attr("class"); 
+7
Aug 17 '11 at 7:29 a.m.
source share

Keep it simple!

 var classes = $(this).parent('div').attr('class'); 
+2
Mar 29 '13 at 19:50
source share



All Articles