How to select first parent DIV using jQuery?
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.
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(' ');