In my current project, I've implemented a custom micro-library similar to JQuery, but tailored specifically to my needs.
window.$ = function(selector, context, undefined)
{
var getSelectorTest = function(selector, context, undefined)
{
var el;
var selector_key = selector.slice(0, 1),
matches = {
'#': 'getElementById',
'.': 'getElementsByClassName',
'@': 'getElementsByName',
'=': 'getElementsByTagName',
'*': 'querySelectorAll'
}[selector_key],
selector_value = selector.slice(1);
//add fallback for getElementsByClassName is not supported e.g. IE8
if(matches === 'getElementsByClassName' && !document.getElementsByClassName)
{
matches = 'querySelectorAll';
selector_value = selector;
}
// now pass the selector without the key/first character
el = (((context === undefined) ? document: context)[matches](selector_value));
return el;
};
var elem = getSelectorTest(selector, context, undefined);
//Extend elem before returning it
elem.attr = function(name, value) {
if(value)
{
this.setAttribute(name, value);
return this;
}
else
{
return this.getAttribute(name);
}
return elem;
};
Upon executing the below code:
<script>
domReady(function(){ //https://github.com/cms/domready
var el_1 = $('#container-1');
el_1.attr("data-test", "random_value");
});
</script>
My output differs when using IE8:
<div id="container-1" attr="function(name, value) {
if(value)
{
this.setAttribute(name, value);
return this;
}
else
{
return this.getAttribute(name);
}
}" data-test="random_value">
This issue doesn't occur in Chrome and Firefox where the expected output is
<div id="container-1" data-test="random_value">
. How can I resolve this discrepancy?
Note: I'm currently utilizing the 'HTML' tab within IE8 Developer Tools (F12) to investigate this behavior.