Reputation: 1776
function $(e){return document.querySelector(e)}
I use this as a shorthand for querySelector
.
For example: $('.MainClass').style.display='none';
It actually works too, but Chromes Console logger shows an error:
Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': '[object HTMLDocument]' is not a valid selector.
Which is weird, because when using $('cssslectorhere')
it still works. The reason I did this because I was so used to jQuery, that I liked the $
symbol. But I hate seeing that error in the console log, anyway to remove it?
Upvotes: 1
Views: 106
Reputation: 707218
It sounds like your code is somewhere trying to pass the document
object instead of a string selector as in $(document)
. You could work around that by changing your code to this:
function $(e){
if (typeof e === "string") {
return document.querySelector(e);
} else {
return e;
}
}
Then, this would work with any DOM object that you passed such as document
or document.body
.
Or, you could make it a quite a bit more foolproof:
//Returns true if it is a DOM node
function isNode(o){
return (
typeof Node === "object" ? o instanceof Node :
o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
);
}
function $(e) {
if (typeof e === "string") {
return document.querySelector(e);
} else if isNode(e) {
return e;
} else {
throw new Error("arg in $(arg) must be selector string or DOM node");
}
}
See this prior answer for a discussion/reference for the isNode()
function.
Upvotes: 0
Reputation: 43842
You have not provided all of the code. Somewhere, you're doing this:
$(document)
This works in jQuery, but it will not work with querySelector
because it isn't a selector.
Either remove that usage, or change your $
function to handle document
.
function $(e){
return e === document ? document : document.querySelector(e);
}
Upvotes: 4