ironboy
10-07-2011, 10:13 PM
In answering different questions here I often find myself reinventing the wheel when it comes to how to select elements, using rigid DOM methods like selectElementsByTagName etc.
I do that because I understand that you can't expect people to have jQuery or a similar library installed.
Still I suspect it would be easier and make the rest of the code clearer when answering a question/writing an example if a small selector engine was included:
function $(sel){
// ironboy: a minimal selector engine (for use in teaching)
sel = '* {display:block !important; position:absolute !important;'
+ ' left:0}\n' + sel + ' {left:-10050px !important}';
var style = document.createElement('style');
style.type = 'text/css';
style.styleSheet ? (style.styleSheet.cssText = sel) :
style.appendChild(document.createTextNode(sel));
document.getElementsByTagName('head')[0].appendChild(style);
var elsAll = document.getElementsByTagName('*'), els = [];
for(var i = 0; i < elsAll.length; i++){
elsAll[i].offsetLeft < -10000 && els.push(elsAll[i]);
};
style.parentNode.removeChild(style);
els.each = function(func){
for(var i = 0; i < this.length;i++){func.call(this[i])}
};
return els
};
I do that because I understand that you can't expect people to have jQuery or a similar library installed.
Still I suspect it would be easier and make the rest of the code clearer when answering a question/writing an example if a small selector engine was included:
function $(sel){
// ironboy: a minimal selector engine (for use in teaching)
sel = '* {display:block !important; position:absolute !important;'
+ ' left:0}\n' + sel + ' {left:-10050px !important}';
var style = document.createElement('style');
style.type = 'text/css';
style.styleSheet ? (style.styleSheet.cssText = sel) :
style.appendChild(document.createTextNode(sel));
document.getElementsByTagName('head')[0].appendChild(style);
var elsAll = document.getElementsByTagName('*'), els = [];
for(var i = 0; i < elsAll.length; i++){
elsAll[i].offsetLeft < -10000 && els.push(elsAll[i]);
};
style.parentNode.removeChild(style);
els.each = function(func){
for(var i = 0; i < this.length;i++){func.call(this[i])}
};
return els
};