Looking through the code in the Dojo library for dojo / query, it looks like they are using document.getElementById
by default if the selector passed as an identifier selector.
For example, if:
query("#myId")
This will be behind the scenes:
document.getElementById("myId")
This is fine for querying nodes in a window document, but what if you create nodes not yet placed in the document? If I create a node in memory to put in the DOM later, and I need to request this node by ID, I cannot do this. Because this node is not yet in the document.
I understand that this is how jQuery works, but jQuery differs from the fact that the approach for querying by identifier or another selector (class, attribute, etc.) is the same. For instance:
$("#myId") $(".myClass") $("div[align=center]")
The same approach. So the default document.getElementById
in this case is suitable for me.
With Dojo its pretty misleading in light of the fact that Dojo offers a separate function that serves as an alias to getElementById (dom.byId)
. If I wanted the ID request against the actual document, I would use this. If I use a dojo / query selector, then I want to be able to query a document or context node.
Dojo uses the lite.js selection mechanism in situations where a viable selector mechanism is available. At the beginning of the file there is a βquick pathβ block, which actually makes it default to dom.byId
. If I comment on this block, the engine will revert to using querySelectorAll
, which in turn fixes this problem.
Can someone explain the reason for Dojo to do this? Or if there is a viable workaround that doesn't require me to comment on Dojo code? One approach I've seen is to use data attributes instead of identifiers that fake the engine, but it just seems lame.
EDIT
Note. You can pass the context node to the dojo / request when requested, but in Dojo, even if you create the node outside the DOM using dom-construct, the ownerDocument of this node is still window.document. In other words:
var node = domConstruct.toDom('<div><p><span id="myId">Content</span></p></div>'); var doc = node.ownerDocument;
will cause the doc to be window.document. So something like:
doc.getElementById("myId")
will fail. As it will be:
var results = query("#myId", node);
Because Dojo code is looking for ownerDocument from 'node', which again is window.document