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
Element.addMethods({

  	// Get/Set attribute from/on element
  	attr: function(element, attrName, attrValue)
  	{
  		if (attrValue != undefined)
  			element.writeAttribute(attrName,attrValue);
  		else
  			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 😉

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Join the Conversation

4 Comments

Leave a comment

Your email address will not be published.

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