(If it makes any difference, I'm working on a web component.)
If I have the following:
<!-- Assume a decently-sized web page with lots of elements before and after all this -->
<form>
<input type="hidden" id="foo" name="foo" value="bar" />
</form>
<script>
let myForm = document.querySelector('form');
</script>
…and I want to select the hidden field, which is faster/better?
A)
let field = document.querySelector('#foo');
B)
let field = myForm.querySelector('#foo');
In the case of an ID selector, I think A is likely to be faster.
IDs are supposed to be unique, so the browser almost certainly has an index of all the IDs. Looking up an ID in document will use this index to find the element as quickly as possible.
But if you query for the ID nested in another element, it will assume that you're violating this expectation, and it will have to do an actual search within that element. This is difficult to optimize, and there's little incentive to do so since it's not a valid DOM.
It's possible that the browser will keep track of which IDs have been duplicated. If foo is not duplicated, B could be optimized to be equivalent to A.
So B is at best equivalent to A, but it could be worse.