why document.querySelectorAll does not work after being assigned to a variable?
Asked
Active
Viewed 333 times
0

Grigory Hatsevich
- 399
- 2
- 9
-
The `.bind()` solution in the duplicate is unfortunate because you don't always want to select from the `document`. Instead, make a function that will accept one or two arguments. If only one, it should be a string and should select from `document`. If two, the first argument should be the context and the second is the selector string. – Mar 07 '17 at 21:36
-
...`function qsa(ctx, sel) { if (typeof ctx === "string") { sel = ctx; ctx = document } return ctx.querySelectorAll(sel) }` Then you can pass a string or an element and a string. `qsa("li")` or `qsa(myElemCtx, "li")` – Mar 07 '17 at 21:37
1 Answers
4
Since are no longer calling it in the context of document
, you have changed the value of this
inside the function.
The function depends on the value of this
being document
to work.
If you explicitly set the value of this
, then it works:
var qsa = document.querySelectorAll;
console.log(qsa.call(document, "li").length);
<ul><li>.<li>.<li>.</ul>

Quentin
- 914,110
- 126
- 1,211
- 1,335
-
1
-
Regarding the answer, if u want direct thisContext, It'd also be appropriate to bind querySelectorAll with thisContext. – Mar 07 '17 at 21:23
-
1