Skip to content

Instantly share code, notes, and snippets.

@Fetz
Created December 3, 2015 10:51
Show Gist options
  • Save Fetz/e72c95ab6a06deec7fd5 to your computer and use it in GitHub Desktop.
Save Fetz/e72c95ab6a06deec7fd5 to your computer and use it in GitHub Desktop.
How to add querySelectorAll to ie7
function querySelectorAll(el, query) {
if (el.querySelectorAll) return el.querySelectorAll(query);
var style = document.createStyleSheet();
var q = query.replace(/\[for\b/gi, '[htmlFor').split(',');
var results = [];
for (var i = q.length; i--;) {
style.addRule(q[i], 'k:v');
for (var j=el.all.length; j--;) {
el.all[j].currentStyle.k && results.push(el.all[j]);
}
style.removeRule(0);
}
return results;
}
@WebReflection
Copy link

I know I'm late to the party but this is an O(n^m) instead of an O(2n+m) as shown here:

function querySelectorAll(el, query) {
  if (el.querySelectorAll) return el.querySelectorAll(query);

  var style = document.createStyleSheet();
  var q = query.replace(/\[for\b/gi, '[htmlFor').split(',');
  var results = [];
  for (var i = q.length; i--; style.addRule(q[i], 'k:v'));
  for (var j=el.all.length; j--;) {
    el.all[j].currentStyle.k && results.push(el.all[j]);
  }
  for (var i = q.length; i--; style.removeRule(i));
  return results;
}

btw, nice little hack.

Best regards

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