Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the order objects are return by a jQuery selector specified?

Tags:

jquery

All jQuery selectors return an array of objects. Are these objects always in the same order as they are in the HTML? Can I rely on this?

like image 841
user28584 Avatar asked Oct 28 '09 09:10

user28584


People also ask

What does jQuery selector return?

The jQuery Object: The Wrapped Set: Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example).

How do jQuery selectors work?

jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.

Which is the correct jQuery selector to select all elements?

The jQuery #id selector selects an HTML element based on the element id attribute. Following is a simple syntax of a #id selector: $(document).


2 Answers

Yes.
The jQuery 1.3.2 release notes say:

Elements Returned in Document Order

This is a change to jQuery's selector engine that re-orders the returned results to be in document order, instead of the order in which the selectors were passed in. This change was done in order to be in compliance with the Selectors API specification (which jQuery uses, internally, in browsers that support it).

This wasn't the case on jQuery 1.3:

The order of "a, b, c" style selectors may change. Browsers that support querySelectorAll (Safari, Firefox 3.5+, Opera 10+, IE 8+) will return the elements in document order, other browsers will (currently) return them in the order specified. In 1.3.2 and later release all comma-separated selectors will be returned in document order.

like image 81
Kobi Avatar answered Nov 15 '22 14:11

Kobi


There may be some exceptions, for example from the prevAll() documentation:

"Given a jQuery object that represents a set of DOM elements, the .prevAll() method searches through the predecessors of these elements in the DOM tree and construct a new jQuery object from the matching elements; the elements are returned in order beginning with the closest sibling."

http://api.jquery.com/prevAll/

like image 45
Emery Lapinski Avatar answered Nov 15 '22 14:11

Emery Lapinski