Skip to content

Instantly share code, notes, and snippets.

@yoavniran
Last active May 6, 2024 12:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoavniran/7f6aff3d5b1c4bbfad78 to your computer and use it in GitHub Desktop.
Save yoavniran/7f6aff3d5b1c4bbfad78 to your computer and use it in GitHub Desktop.
function to select element even using a numeric class name on IE8
var _selectorRgx = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/ ; //stole from jquery, to be used to quicken selector if simple class/id/tag selector used
/**
* stole the regex logic from jquery, added the support for classname selector starting with a number on IE8
* for example selector = ".1111" will work with this code even on IE8
**/
function select(selector) {
var match = _selectorRgx.exec(selector),
doc = window.document,
res;
if (match[1]) { //id selector
res = doc.getElementById(match[1]);
}
else if (match[3]) { //class selector
if (doc.getElementsByClassName) {
res = doc.getElementsByClassName(match[3]);
res = res[0];
}
else {//IE8 - no getElementsByClassName :(
selector = "." + match[3].replace(/^\d/, function (char) { //will only replace the first character if its a number with hex so it works
return "\\" + char.charCodeAt(0).toString(16) + " ";
});
res = doc.querySelector(selector); //selector cant start with a number, its considered invalid
}
}
else if (match[2]) { //tag selector
res = doc.getElementsByTagName(match[2]);
res = res[0];
}
if (!res) {
res = doc.querySelector(selector);
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment