Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the order of elements in a jQuery-wrapped set always match the order in which the elements appear in the markup?

Tags:

jquery

dom

Is the order of the elements in jQuery wrapped set guaranteed to match the order the elements appear in the markup?

I ask because I need to perform an operation on a set of nested elements, and I need to always do the operation in order of the nesting.

Can I just run the operation using the .each() iterator on the matched set and always get the right order, or do I need to find some other way to guarantee the operation order matches the nesting order?

like image 561
Tim Sheiner Avatar asked Jul 08 '09 18:07

Tim Sheiner


2 Answers

Just been looking at this myself. jQuery does return things in document order as per the following article:

http://docs.jquery.com/Release:jQuery_1.3.2

So, if you select some ids as such:

$("#id1, #id2, #id3")

Then they will be returned in the order they appear in the DOM, not necessarily in the order they are given. Its certainly worth being aware of this when you upgrade from earlier to later version of jQuery.

like image 152
James Wiseman Avatar answered Sep 20 '22 15:09

James Wiseman


jQuery will match your query top down so the matched set will always be the same.

like image 37
RedWolves Avatar answered Sep 20 '22 15:09

RedWolves