Hey my question is relatively simple i guess.
I wonder if jQuerys each() method scans the page in element order or not, i can’t seem to find the answer.
I mean let’s say i have :
<div>
<span class="example">1</span>
<span class="example>2</span>
</div>
<div>
<span class="example">3</span>
</div>
And i write the following :
$('.example').each(function(index) {
alert(index + ': ' + $(this).text());
});
Will i always get “123”? i mean if the elements are scattered more then that…
Yes, on a normal selector query like this, the objects are sorted into DOM order in the jQuery object and that jQuery array order is the order they are presented in the
.each()iteration. There is an explicit step in the construction of the jQuery object (in the jQuery code) where all the DOM elements are sorted into page order top to bottom.There are some jQuery methods like
.prev()or.prevAll()that explicitly do not return elements in document order, but rather in previous order (from the starting point going up).