xstyle_transparentThe short answer is: no, dojo/query is not guaranteed to return elements in the same order as they appear in the DOM.

Dojo’s query module is designed to use the DOM’s querySelectorAll method, if available. Otherwise, it uses a CSS selector library. While querySelectorAll does return elements in order, the selector engines provided with Dojo (dojo/selector/acme and dojo/selector/lite) have been optimized for speed without strict adherence to element order. This means you may often find that they return elements in order, but this is not guaranteed.

Dojo can be configured to use a specific selector engine, such as the Sizzle selector engine, which will return elements in the order they appear in the DOM. To apply the configuration globally, set it in your Dojo configuration:

<script data-dojo-config="selectorEngine: 'sizzle/sizzle'"
    src="dojo/dojo.js">
</script>

If you want to configure dojo/query to use a specific selector engine only for a certain module, you can specify it when loading the query module using the AMD module loader plugin syntax:

// app/useSizzle
define(["dojo/query!sizzle/sizzle"], function(query){
  // We'll be using the Sizzle engine here
  query(".someClass:custom-pseudo").style("color", "red");
});

// app/useLite
define(["dojo/query!dojo/selector/lite"], function(query){
  // We'll be using the Lite engine here
  query(".someClass:custom-pseudo").style("color", "red");
});

You will need to download a version of Sizzle wrapped in AMD for easy integration with Dojo via GitHub.

Alternatives

If you cannot load a custom selector engine, and your application relies on knowing the element order, there are some methods that may be helpful: