views:

292

answers:

3

Hi

Is there any equivalent in Prototype for the jQuery closest function?

http://api.jquery.com/closest/

thanks

A: 

.next('.className') or .next('divId')

There is also .previous(), .down() and .up(), depending on where you're looking.

Diodeus
+5  A: 

You can use the up method. It is not quite equivalent, since closest also considers the current element. So you would need to first test your selected element to see if it matches your criteria, if it does not, use the up-method:

jQuery:
return $('#id').closest('li');

Prototype:
var element = $('id')
return element.match('li') ? element : element.up('li');
}

Comparison:

.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

You can easily extend Prototype to include this method for all elements like so:

// Adds a closest-method (equivalent to the jQuery method) to all 
// extended Prototype DOM elements
Element.addMethods({
   closest: function closest (element, cssRule) {
      var $element = $(element);
      // Return if we don't find an element to work with.
      if(!$element) {
         return;
      }
      return $element.match(cssRule) ? $element : $element.up(cssRule);
   }
});
PatrikAkerstrand
A: 

As far as I know, internal vars in prototypejs don't need the $ for example var $element should probably read var element = $(element);

Matt
They don't need it in jQuery either. I just don't want to override the parameter element. By saying var $element = $(element), I am sure that $element is an extended element, whereas element can be a string id.
PatrikAkerstrand