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.
CodePudding user response:
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);
CodePudding user response:
const get = document.querySelector.bind(document);
this will work as it will preserve the context of document to querySelector's this
get('*') // will work while defining it as const get = document.querySelector wouldnt
edit: why the hell the downvote it's true
CodePudding user response:
I'd recommend using Jquery. It's widely accepted across the front-end industry, does what you are asking to get help for, and you can use it for other organization level projects instead of only for personal projects.
Just include this line of code in your html header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>