views:

100

answers:

1

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?

+1  A: 

I've cooked up what I suppose could stay as a viable solution; is there anything fundamentally bad about using this method to chain-modify a collection of elements?

<script>
_ = function()
 {
    for (x = 0; x < arguments[0].length; x++)
     {
     for (y = 0; y < arguments[1].length; y++)
      {
      eval('arguments[0][x]' + '.' + arguments[1][y]);
      }
     }
 }
</script>

Usage:

divs = document.getElementsByTagName('div');
_(divs, ["style.color = 'red'", "innerHTML += x"]);
Hexagon Theory
Yes, you don't need eval for this.Also since you actually have only 2 arguments, why not naming them and using arguments[]array?
BYK