Horen
Horen

Reputation: 11382

Change / reverse order of jQuery parents() selector

I am using the following selector for an each loop in jQuery:

$("#myid").parents().andSelf().each(function({})

The selector returns an object like this:

object[html, body, div#global_container, div#content, div#myarea, span.myclass, div#myid]

That means the each loop will start with the furthest parent and then eventually ends with self

How can I reverse that order so that the each loop will start with self and work its way up the dom tree instead of down?

Upvotes: 3

Views: 3218

Answers (5)

Eugene Lyushenko
Eugene Lyushenko

Reputation: 7

I guess .reverse() might be pretty expensive for a large node sets, so I would recomment using

$.merge($el, $el.parents()).each(function(){ ... })

Upvotes: 0

Bell
Bell

Reputation: 455

A nice way to add a reverse function to jQuery:

jQuery.fn.reverse = [].reverse

The Array.reverse is available in virtually all browsers: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

Upvotes: 1

wakooka
wakooka

Reputation: 1428

In order to make reverse() work you need to change your jQuery object to an array :

var elements = $("#myid").parents().andSelf();
elements.toArray().reverse().each(function() {} );

http://jsfiddle.net/6VVAD/

EDIT : The .each() function won't work that way because we can't chain it from a non-jQuery object as @scoota269 mentionned

I fixed it by passing the collection into the each function like so :

var elements = $("#myid").parents().andSelf();
var reversed_elements = elements.toArray().reverse();

jQuery.each( reversed_elements, function(i, elem) {
     console.log(elem , i)
});
​

Upvotes: 5

scottlimmer
scottlimmer

Reputation: 2278

$($("#myid").parents().andSelf().toArray().reverse()).each(function({})

Upvotes: 0

Magus
Magus

Reputation: 15104

You can use the reverse array method.

Array.reverse($("#myid").parents().andSelf());

Be aware that the reverse function is not available on all browsers. But you can use es5-shim.js to fix that.

Upvotes: 1

Related Questions