Skip to content

Instantly share code, notes, and snippets.

@c3r38r170
Last active February 2, 2021 20:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c3r38r170/ec4319fe9b56707deef13045507eabbc to your computer and use it in GitHub Desktop.
Save c3r38r170/ec4319fe9b56707deef13045507eabbc to your computer and use it in GitHub Desktop.
A very good querySelector / querySelectorAll / getElementById / getElementByName / etc. wrapper.
//Some constants.
const ALL=true,ONLY_ONE=false;
//getElementById quick wrapper.
const gEt=id=>document.getElementById(id);
//The actual stuff.
function SqS(selector,amount=ONLY_ONE,root=document){
if(selector instanceof Node)
return selector;
if(!('string'==typeof selector || selector instanceof String))
return false;
let results
,selectorInfo={
rest:selector.slice(1)
,isComplex:false
};
for(let complexChar of [' ','>',':','[','.','#',',','+','~'])
if(selectorInfo.rest.includes(complexChar)){
selectorInfo.isComplex=true;
break;
}
if(selectorInfo.isComplex)
if(!amount||amount===1)
return root.querySelector(selector)
else if(amount===true)
return root.querySelectorAll(selector);
else results=root.querySelectorAll(selector);
else switch(selector[0]){
case '#':
return document.getElementById(selectorInfo.rest);
case '.':
results=root.getElementsByClassName(selectorInfo.rest);
break;
case '[':
let nameMatch=/^\[name="([^"]*)"\]$/.exec(selector);
if(nameMatch)
results=document.getElementsByName(nameMatch[1]);
break;
case ':':
break;
default:
results=root.getElementsByTagName(selector);
}
//results is falsey (null) when the selector is a pseudoclass, or is '[name=""]'.
if(!amount||amount===1)
return results?results[0]:document.querySelector(selector);
else if(amount===true)
return results?results:document.querySelectorAll(selector);
else{
if(!results)
results=document.querySelectorAll(selector);
if(amount>=results.length)
return results;
//Remember results is not an array, but a NodeList, and this is faster than [].splice.call(...
let chosen=[];
for(let i=0;i<amount;i++)
chosen.push(results[i]);
return chosen;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment