Created
March 25, 2013 06:47
-
-
Save MoOx/5235317 to your computer and use it in GitHub Desktop.
Unfinished querySelector polyfill supposed to work on IE6+
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// querySelectorAll polyfill | |
(function(window){ | |
var document = window.document; | |
//No need to polyfill | |
if(document.querySelector) { | |
return; | |
} | |
var polyfill_querySelectorAll = function (element, selector) { | |
var head = document.getElementsByTagName('head')[0], | |
styleTag = document.createElement('style'); | |
head.appendChild(styleTag); | |
element.id = element.id || 'querySelectorAll_' + (new Date().getTime()); | |
document.__qsaels = []; | |
styleTag.styleSheet.cssText = '#' + element.id + ' ' + selector + "{x:expression(document.__qsaels.push(this))}"; | |
// @todo found something cleaner to force expression execution | |
window.scrollBy(0, 0); | |
return document.__qsaels; | |
}; | |
var polyfill_querySelector = function(element, selector) { | |
// @todo make this more bulletproof | |
return querySelectorAll(element, selector)[0]; | |
}; | |
function querySelectorAll(selector){ | |
return polyfill_querySelectorAll.call(this, selector); | |
} | |
function querySelector(selector){ | |
return polyfill_querySelector.call(this, selector); | |
} | |
function addPolyfill(obj, i){ | |
if((i = obj.length)) { | |
while(i--) { | |
obj[i].querySelectorAll = querySelectorAll; | |
obj[i].querySelector = querySelector; | |
} | |
} | |
else { | |
obj.querySelectorAll = querySelectorAll; | |
obj.querySelector = querySelector; | |
} | |
return obj; | |
} | |
addPolyfill([document, window]); | |
if('Element' in window) { | |
window.Element.prototype.querySelectorAll = querySelectorAll; | |
window.Element.prototype.querySelector = querySelector; | |
return; | |
} | |
// ie < 8 | |
function applyPolyfill(fn) { | |
var oldFn = document[fn]; | |
document[fn] = function(arg) { | |
return addPolyfill(oldFn(arg)); | |
}; | |
} | |
//Make sure we also init at domReady | |
document.attachEvent('onreadystatechange', function(){ | |
addPolyfill(document.all); | |
}); | |
addPolyfill(document.all); | |
var hijackFn = ['getElementsByTagName', 'getElementById', 'createElement']; | |
for(var fn in hijackFn) { | |
applyPolyfill(hijackFn[fn]); | |
} | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment