What's going on should be pretty basic, I've "dumbed down" everything to a simple example to hopefully be better understandable here.
I declare a "global" function in one of my scripts:
function byClass(cl)
{
return arguments[1]?
arguments[1].GetElementsByClassName(cl):
document.getElementsByClassName(cl);
}
What it does is: you call byClass() with a string argument (=cl) and it returns a document.getElementsByClassName result. If you also specify an Element of the page as the optional 2nd argument, then the function will perform the .getElementsByClassName only "inside" of the specified element.
Example:
<span class="inner">Outside</span>
<p id="outer">
<span class="inner">Inside</span>
</p>
var both=byClass('inner'); ==> [both 1st and 2nd span]
var out=document.getElementById('outer');
var in =byClass('inner',out); ==> [only 2nd span from inside P element]
What I want to happen now is "attach" that function to the HTMLElement Prototype like so:
HTMLElement.prototype.byClass=function(cl){byClass(cl,this);}
So when .byClass() is added to an element in the code, it will perform the byClass function just "inside" the element it was attached to. Applied as code, this will work something like so:
var out=document.getElementById('outer');
var in =out.byClass('inner'); ==> [only 2nd span from inside P]
This all works fine, having no trouble so far.
However, when adding a simple byClass() call to an element's "onClick" event, it doesn't perform the global byClass() but basically a this.byClass() call "inside" the element that triggered it.
var out=document.getElementById('outer');
var in1=byClass('inner'); ==> [works as expected]
var in2=out.byClass('inner'); ==> [works as expected]
but
<input type="button" onclick="console.debug(byClass('inner'));">
will perform an element-specific this.byClass() instead of the global byClass() when clicked.
How can I avoid that...? I'm lost.
I know I could call it as window.byClass() from the onClick event, but I want to keep things simple and leave nothing up to my luck with "maybe I won't forget adding window. before it"...
Grateful for any help or ideas!
No jQuery please. No "don't extend the DOM" comments please.
Thank you. :)