Skip to content

Instantly share code, notes, and snippets.

@jonathan-annett
Last active October 30, 2022 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathan-annett/0fec43abde68ddd6c6514e98ef082854 to your computer and use it in GitHub Desktop.
Save jonathan-annett/0fec43abde68ddd6c6514e98ef082854 to your computer and use it in GitHub Desktop.
when you don't want to use jquery
(function(){
const W=window,D=document;
W.qs=function(q, d) {
return (d ? d : D).querySelector(q);
};
P("tag","s", "");
P("id","","#");
P("class","es",".");
function P(x,a,p) {
W.qs[x] = new Proxy({},{
get(t, q) {
return D.querySelector(p+q);
}
});
if (a) {
W.qs[x+a] = new Proxy({},{
get(t, q) {
let c = D.querySelectorAll(p+q);
return c ? Array.from(c) : [];
}
});
}
}
})();
!function(){let e=window,t=document;function r(r,n,l){e.qs[r]=new Proxy({},{get:(e,r)=>t.querySelector(l+r)}),n&&(e.qs[r+n]=new Proxy({},{get(e,r){let n=t.querySelectorAll(l+r);return n?Array.from(n):[]}}))}e.qs=function(e,r){return(r||t).querySelector(e)},r("tag","s",""),r("id","","#"),r("class","es",".")}();
// qs as a function : qs(query,element) ..... element defaults to document
let whatever = qs("#whatever"); // use as shorthand for document.querySelector(...)
qs("div",whatever).classList.add("thing"); // add "thing" class to first div in whatever
// proxified id/class/tag access
qs.id.someid.innerHTML = "hello world"; // update the someid element's innerHTML
qs.classes.myclass.forEach((x)=>{ x.addEventListener("click",myclicker) });// add myclicker function to each myclass element
qs.tag.body.background = "black";// change the body background style to black
let textInside = qs.tags.div.some( (x) => x.textContent.indexOf("text") >= 0 ); if any divs contain the string "text", set a boolean
@jonathan-annett
Copy link
Author

proxies available:

qs.id - returns single element or null
qs.class - returns single element or null (returns first element if more that one of same class exists)
qs.classes - returns array of elements or an empty array
qs.tag - returns single element or null
qs.tags - returns array of elements or an empty array

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment