Reputation:
Why did i get an this kind of Error ? Basically, I can short my code like this.
const log = console.log;
So why can't we have this one?
const _search = document.querySeletor;
Upvotes: 2
Views: 155
Reputation: 370689
querySelector
can be called on many things, not just the document
, for example:
const outer = document.querySelector('#outer');
const inner = outer.querySelector('div'); // querySelector called on `outer`
console.log(inner);
<div id="outer">
<div id="inner">
</div>
</div>
The querySelector
method must have a root element from which to search from, which it identifies by the calling context of the function (the this
value used inside it). In the above snippet, outer.querySelector('div')
selects a div
element which is a child of outer
. Simiarly, with document.querySelector
, you select a child anywhere in the document (but not, for example, in elements that exist, but are not attached to the document).
But without a calling context (eg, if you assign querySelector
to a standalone variable), the method does not know what root element to search from, so it throws an error.
You can shorten it by .bind
ing the function to the document first, so that it has the appropriate calling context when invoked:
const qs = document.querySelector.bind(document);
console.log(qs('#inner'));
<div id="outer">
<div id="inner">
</div>
</div>
Upvotes: 3