Adding DOM methods with Prototype

July 11, 2007 code 2 min read

I just discovered that prototype has a really cool way to add methods to all instances of any tag. Simply call Element.addMethods(tagname, methods). For example, here’s how I added a request method to anchors, which will just make an ajax call for the anchor’s href:

if (!window.Anchor) { var Anchor = new Object(); }

Anchor.Methods = {
  request: function(anchor, options) {
    anchor = $(anchor)
    options = Object.extend({method: 'get'}, options || {});
    return new Ajax.Request(anchor.readAttribute('href'), options);
Element.addMethods('a', Anchor.Methods);

So now I can go through and hijack links with a specific tag name and just call request() on them:

$$('a.jax').each(function (link) {
  link.observe('click', function(event) {
    link.request({evalScripts: true});
This content is open source. Suggest Improvements.


avatar of Brandon Keepers I am Brandon Keepers, and I work at GitHub on making Open Source more approachable, effective, and ubiquitous. I tend to think like an engineer, work like an artist, dream like an astronaut, love like a human, and sleep like a baby.