Blake Plumb
Blake Plumb

Reputation: 7219

Get all parents of an element including the element itself

I am trying to create an array of all the elements to where the user clicked in a content editable div. I have this working with the following code.

 var els = [];
 var target = event.target;
 while (target){ //Create an array of parent elements
    els.push(target); //Push target to the back of the array
    target = target.parentNode; 
}

But I was wondering if I could reduce this to one line with jQuery. jQuery .parents() almost gets me there but it doesn't include the first event.target

var els = $(event.target).parents();

Is there a way to include the element itself with .parents() or is there a better way of doing this?

Upvotes: 2

Views: 1496

Answers (2)

Treborbob
Treborbob

Reputation: 1221

How about andSelf ?

var els = $(event.target).parents().andSelf();

Mine would get you, great-grandparent, grandparent, parent, self.

If you want: self, parent, grandparent, great-grandparent, try extending Jquery with this:

$.fn.reverse = [].reverse;

and then doing:

var els = `$(event.target).parents().andSelf().reverse();

Example: jsFiddle

Upvotes: 5

Denys Séguret
Denys Séguret

Reputation: 382514

You can use add :

var els = $(event.target).parents().add(event.target);

or, if you want them in a different order :

var els = $(event.target).add($(event.target).parents());

If what you need is an array (ie not a jQuery object), you can use reverse :

var els = $(event.target).parents().add(event.target).get().reverse();

Upvotes: 3

Related Questions