Skip to content

Instantly share code, notes, and snippets.

@ralphholzmann
Forked from garann/gist:1038401
Created June 21, 2011 18:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ralphholzmann/1038554 to your computer and use it in GitHub Desktop.
Save ralphholzmann/1038554 to your computer and use it in GitHub Desktop.
Challenge Accepted.
getEl = (function (doc) {
var getElementsByClassName = (function () {
return doc.getElementsByClassName ?
function (selector) {
return doc.getElementsByClassName(selector.split('.').pop());
} : function (selector) {
var parts = selector.split("."),
tags = document.getElementsByTagName(parts[0] || "*"),
matches = [],
classes, i, iLength, c, cLength;
for (i = 0, iLength = tags.length; i < iLength; i++) {
classes = ("" + tags[i].className).split(" ");
for (c = 0, cLength = classes.length; c < cLength; c++) {
if (classes[c] == parts[1]) {
matches.push(tags[i]);
break;
}
}
}
return matches;
}
})();
return doc.querySelectorAll ?
function (selector) {
return doc.querySelectorAll(selector);
} : function (selector) {
var id;
if ((id = selector.split("#")).length > 1) {
return document.getElementById(id.pop());
} else {
return getElementsByClassName(selector);
}
}
})(document);
@garann
Copy link

garann commented Jun 21, 2011

Ah, nice, but I don't know if getElementsByClassName works for this use case.. ideally they'd have a tag name, too. I guess it's nice to offer the flexibility though. HMMMMM.

@danheberden
Copy link

Sounds like you need sizzle?

@garann
Copy link

garann commented Jun 21, 2011

Don't think I need the whole thing.. Just have to allow #id or tag.class - should always be one of those. I guess I could take part of it.

@danheberden
Copy link

ooh, works with tag name http://jsfiddle.net/danheberden/rEnjn/ - actually, nvm :( fails on ie6,7

@garann
Copy link

garann commented Jun 21, 2011

Yeah, works great when it uses queryselectorall. :D

@ralphholzmann
Copy link
Author

NVM

@garann
Copy link

garann commented Jun 21, 2011

Ha, I just removed that, cause I guess it's only faster in webkit.. Oops. But I forgot to add the pipe in the jsperf that the original gist had to prevent that problem.

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