Javascript Tips & Tricks

Prototype equivalents for jQuery functions

Magento use prototype javascript library a lot. And if you do not want to mess with other libraries you could port your scripts to Prototype. This article will help you with porting some jQuery functions to Prototype equivalents.

.attr()

Get / set the value of an attribute for a single element or set of elements.

jQuery

$('img').attr('src');
$('img').attr('src', 'new_image.jpg');

Prototype

$('img').readAttribute('src');
$('img').setAttribute('src', 'new_image.jpg');

.closest()

Get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

jQuery

$('img').closest('div');

Prototype

$('img').up('div');

up method is not quite equivalent, since closest also considers the current element.

.closest()

  • Begins with the current element
  • Travels up the DOM tree until it finds a match for the supplied selector
  • Returns a jQuery object that contains zero or one element

.up()

  • Begins with the parent element
  • Travels up the DOM tree until it finds a match for the supplied selector
  • Returns an extended Element object, or undefined if it doesn’t match

.trigger()

Execute all handlers and behaviors attached to the matched elements for the given event type. There is no equivalent in Prototype. You need to create it.

jQuery

$('a').trigger('click');

Prototype

Element.prototype.triggerEvent = function(eventName)
{
    if (document.createEvent)
    {
        var evt = document.createEvent('HTMLEvents');
        evt.initEvent(eventName, true, true);

        return this.dispatchEvent(evt);
    }

    if (this.fireEvent)
        return this.fireEvent('on' + eventName);
}
$('a').triggerEvent('click');

If you have more Prototype equivalents for jQuery functions – please post it in comments and we will add it to the article

2 thoughts on “Prototype equivalents for jQuery functions

Leave a Reply

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