Backdropping jQuery functions into PrototypeJS

One of the functions I use quite regularly when working with jQuery is .attr(). Right now – at work – I’m fiddling around in Prototype, and noticed I kept on writing .attr() which – quite evidently – doesn’t exist. Okay, I can use Prototype’s .readAttribute() and .writeAttribute() but that’s quite a hassle: I want one function to set and get attributes, just as jQuery offers. Time to extend Prototype with some jQuery functionality 😉

As provided by the Prototype API, use Element.addMethods() to extend Element. Five minutes later, this implementation came out:

// Bramus jQuery backdrops

  	// Get/Set attribute from/on element
  	attr: function(element, attrName, attrValue)
  		if (attrValue != undefined)
  			return element.readAttribute(attrName);

  		return element;


Updated: added return element; to enable chaining 😉

I know the implementation isn’t as extended as it is in Prototype and jQuery but it’s a good start of course 😉

And ooh, if you’re looking to mimic jQuery’s chaining functionality in Prototype, use .invoke() 😉

// jQuery - add classname and rel 'bramus' on all h3's inside the #myDiv div
$('div#myDiv').find('h3').addClass('bramus').attr('rel','bramus'); // I know, this can be written as $('div#myDiv h3'). ...

// Prototype - add classname and rel 'bramus' on all h3's inside the #myDiv div
$('myDiv').select('h3').invoke('addClassName', 'bramus').invoke('attr', 'rel', 'bramus'); // I know, this can be written as $$('div#myDiv h3'). ...

Happy coding!

Note: If you’re wondering why I’m sticking to Prototype and not moving to jQuery: the whole site has quite a few (not to say: a lot) Prototype based scripts that are interlinked. Switching isn’t possible right now 😉

Join the Conversation


Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.