How to select first parent DIV using jQuery?

JavascriptJqueryCss Selectors

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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(' ');

Solution 3 - Javascript

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

var div = $(this).parent("div");
var _class = div.attr("class");

Solution 4 - Javascript

Keep it simple!

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

Solution 5 - Javascript

two of the best options are

$(this).parent("div:first")

$(this).parent().closest('div')

and of course you can find the class attr by

$(this).parent("div:first").attr("class")

$(this).parent().closest('div').attr("class")

and for you

$(this).parent("div:first").attr("class").split(' ')
$(this).parent().closest('div').attr("class").split(' ')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdamView Question on Stackoverflow
Solution 1 - JavascriptShefView Answer on Stackoverflow
Solution 2 - JavascriptTatu UlmanenView Answer on Stackoverflow
Solution 3 - JavascriptEsbenView Answer on Stackoverflow
Solution 4 - JavascriptDaniel WestView Answer on Stackoverflow
Solution 5 - JavascriptJunaid MasoodView Answer on Stackoverflow