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 ;)

Bramus!, javascript, Webdevelopment

4 Responses to Backdropping jQuery functions into PrototypeJS

  1. Kevin says:

    Good article! But I didn’t know you worked for Netlog.com.

  2. Bramus! says:

    @Kevin: Thanks! I started working at Netlog last week, as announced on my other blog: Nieuw in Gent (Did or didn’t I announce the existence of my other blog here? – I did, in a tiny post though) ;)

  3. Pingback: Bram.us » YUI 3 Preview Release

  4. Pingback: Bram.us » Barcamp Ghent

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>