3

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?

5 Answers 5

5

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) }); ​ 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Array.reverse is available in virtually every browser, developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
1

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

1 Comment

After including the line above in your script, you can 'reverse' the order like so: $('#some_selector').reverse();
0

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

9 Comments

There is no in-built reverse() function in jQuery. You could build one yourself though.
Yes but there is a built in one with Javascript. Hence the need to wrap it in a $() to use the each. @RoryMcCrossan
That'c correct, but the way you're using it isn't - your code would throw an error. What I mean is there is no reverse() method of a jQuery object. You would need to use it in the way that @Magnus has.
@RoryMcCrossan Right you are, fixed I believe.
Why the $ sign before Array.reverse ?
|
0

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.