Skip to content

Instantly share code, notes, and snippets.

@Fusselwurm
Created January 30, 2013 14:39
Show Gist options
  • Save Fusselwurm/4673695 to your computer and use it in GitHub Desktop.
Save Fusselwurm/4673695 to your computer and use it in GitHub Desktop.
document.querySelector, document.querySelectorAll for IE7
/*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
*
*/
(function () {
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;
};
// be rly sure not to destroy a thing!
if (document.querySelectorAll || document.querySelector) {
return;
}
document.querySelectorAll = function (selector) {
return select(selector, Infinity);
};
document.querySelector = function (selector) {
return select(selector, 1)[0] || null;
};
}());
Copy link

ghost commented Nov 7, 2016

Thank's

@ShemJM
Copy link

ShemJM commented Nov 30, 2018

Yeah, thanks this helped a lot.

@Fusselwurm
Copy link
Author

Here I am eight years later as GitHub's "customize your pins" feature leads me to this place and the realization that my copy of this long-forgotten hack is my most-starred contribution to the world


because as recently as 2018, people still had to support IE7 ???

763f584e0dbb36d8cff20c035b9135d7

@kafaa-dev
Copy link

Thanks this helped a lot! and answer my curiosity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment