0

In my code I use

$('button').hide();

To hide a button.

I do not want to include jQuery. In the example below I try to define $ as a document.querySelector function.

const $ = document.querySelector;
$('button').style.display = 'none';

I can't use $ when binding the function this way.

Can you explain the reason why this is the case.

Also can you explain how I would be able to bind $ to document.querySelector

Daniel Tate
  • 2,075
  • 4
  • 24
  • 50
user504909
  • 9,119
  • 12
  • 60
  • 109
  • 2
    Does this answer your question? [Why can't I directly assign document.getElementById to a different function?](https://stackoverflow.com/questions/6318704/why-cant-i-directly-assign-document-getelementbyid-to-a-different-function) – Sebastian Simon Jul 03 '20 at 02:18

1 Answers1

0

In your example

const $ = document.querySelector;

We are binding the querySelector function to $ With no document context this will fail since the querySelector function requires the parent document object to know what to query.

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

You can get around this by including the document reference in your function.

const $ = selector => (document.querySelector(selector));

If you prefer more verbose code:

const $ = function(selector) {
    return document.querySelector(selector);
}

Or you can write this as:

function $(selector) {
    return document.querySelector(selector);
}

This post may be related to:

Why can't I directly assign document.getElementById to a different function?

Daniel Tate
  • 2,075
  • 4
  • 24
  • 50