Skip to content
Advertisement

Set variable to method

I want to make a shorthand library for myself, ex: shortening querySelector to get.

would there be a way to return just the method without document?

EXAMPLE:

function get(selector) {
  return .querySelector(selector)
}

Thanks.

Advertisement

Answer

You have to call .querySelector on either the document or an element. It can’t be left off. While you could pass it into the function…

const get = (context, selector) => context.querySelector(selector);
get(document, '.foo');

Having to write document each time you call it would be pretty repetitive. Just put it inside the function, there’s nothing wrong with that.

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

Another option (that I wouldn’t recommend, since it mutates a built-in object) would be to add your method to document.

document.get = function(selector){
  return this.querySelector(selector);
};

or

document.get = (selector) => document.querySelector(selector);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement