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
Bram.us is the technical/geeky weblog of Bram Van Damme (nicknamed Bramus!), a 28 year old geezer raised in Deinze and living in
Good article! But I didn’t know you worked for Netlog.com.
@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)
Pingback: Bram.us » YUI 3 Preview Release
Pingback: Bram.us » Barcamp Ghent