This is—at least at the moment—purely experimentation, but I'm curious: is there a way to attach methods (via prototyping) to collections of elements? I've tested the following code:
<div>a</div>
<div>b</div>
<div>c</div>
<script>
NodeList.prototype._ = function(s)
{
for (x = 0; x < this.length; x++)
{
eval('this[x]' + '.' + s);
}
return this;
}
document.getElementsByTagName('div')._("style.backgroundColor = 'red'")._('innerHTML += x');
</script>
At the moment, it works perfectly in Opera; just as would be expected, the _ method is being called on all of the div elements, and then eval()'ing the string passed to it onto each element in turn. Note that the _ method allows for chaining, and that's been demonstrated as well, calling _ to append the predicted x iterator variable to the innerHTML of each element.
Now, two questions...
First, is there a better way of going about this? I have for the longest wished I could just do document.getElementsByTagName('div').style.backgroundColor = "red";
, but alas, it simply hasn't yet come to be. This is why I am doing this in the first place, and why I named the method so succinctly; I'm trying to emulate it as closely as possible.
Secondly, assuming this is a sane usage, how would I go about getting it to work in Firefox? That browser's equivalent of NodeList
is HTMLCollection
, but trying to prototype the latter simply doesn't succeed. Suggestions?