Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jQuery always iterate through DOMs in order in which they are found in the code?

Say, for example, I have a sortable list:

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

What I want to know is, if I make a jQuery call such as the following:

$.each($('li'), function(key, item) {...});

Can I expect jQuery to go through the entries from top to bottom? I've run a few tests, and tried rearranging items dynamically using jQueryUI, and so far, it seems to always run in order. But can this always be expected? Or is it dumb luck that I've not run into anything so far to make me think otherwise...?

like image 432
Kyle Macey Avatar asked Feb 07 '12 19:02

Kyle Macey


3 Answers

"Can I expect jQuery to go through the entries from top to bottom?"

Yes. They are iterated by numeric index from 0 to length - 1.

The elements will always be returned in the order that they appear in the DOM.

"I've run a few tests, and tried rearranging items dynamically..."

It doesn't give consideration to CSS positioning if that's what you mean. If you're changing their actual location in the DOM, then you'd only see the updates if you re-select them from the DOM.

like image 135
user1106925 Avatar answered Nov 09 '22 11:11

user1106925


It didn't use to, but since jQuery 1.3.2 selectors return elements in the order in which they are found in the DOM.

like image 44
Paolo Bergantino Avatar answered Nov 09 '22 10:11

Paolo Bergantino


There is no where in the docs that promise this behavior, but this the way it's currently implemented.

That said, I can't see a reason why would they change this behavior.

like image 3
gdoron is supporting Monica Avatar answered Nov 09 '22 12:11

gdoron is supporting Monica