Skip to content

Instantly share code, notes, and snippets.

@thomasJang
Forked from Fusselwurm/querySelector.js
Last active August 29, 2015 14:11
Show Gist options
  • Save thomasJang/6ecc21759179708ae11b to your computer and use it in GitHub Desktop.
Save thomasJang/6ecc21759179708ae11b to your computer and use it in GitHub Desktop.
exception for modern browser
/*global document */
/**
* define document.querySelector & document.querySelectorAll for IE7
*
* A not very fast but small hack. The approach is taken from
* http://weblogs.asp.net/bleroy/archive/2009/08/31/queryselectorall-on-old-ie-versions-something-that-doesn-t-work.aspx
*
*/
/*
* exception for modern browser
*/
(function () {
if (document.querySelectorAll || document.querySelector) {
return;
}
if(!document.createStyleSheet) return;
var style = document.createStyleSheet(),
select = function (selector, maxCount) {
var
all = document.all,
l = all.length,
i,
resultSet = [];
style.addRule(selector, "foo:bar");
for (i = 0; i < l; i += 1) {
if (all[i].currentStyle.foo === "bar") {
resultSet.push(all[i]);
if (resultSet.length > maxCount) {
break;
}
}
}
style.removeRule(0);
return resultSet;
};
document.querySelectorAll = function (selector) {
return select(selector, Infinity);
};
document.querySelector = function (selector) {
return select(selector, 1)[0] || null;
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment