Similar to your $$ approach, I created a function (of the same name) that uses a memorization pattern to keep global cleaner and also accounts for a second context parameter... like $$(".class", "#context"). This is needed if you use the chained function find() that happens after $$ is returned; thus it will not be cached alone unless you cache the context object first. I also added boolean parameter to the end (2nd or 3rd parameter depending on if you use context) to force it to go back to the DOM.
Code:
function $$(a, b, c){
var key;
if(c){
key = a + "," + b;
if(!this.hasOwnProperty(key) || c){
this[key] = $(a, b);
}
}
else if(b){
if(typeof b == "boolean"){
key = a;
if(!this.hasOwnProperty(key) || b){
this[key] = $(a);
}
}
else{
key = a + "," + b;
this[key] = $(a, b);
}
}
else{
key = a;
if(!this.hasOwnProperty(key)){
this[key] = $(a);
}
}
return this[key];
}
Usage:
<div class="test">a</div>
<div id="container">
<div class="test">b</div>
</div>
<script>
$$(".test").append("1"); //default behavior
$$(".test", "#container").append("2"); //contextual
$$(".test", "#container").append("3"); //uses cache
$$(".test", "#container", true).append("4"); //forces back to the dome
</script>