Tip - Getting Last Descendant Of An Element

Sometimes there is a need to get last descendant element of same element. Prototype provides a method to get firstDescendant, but not the last one.
With Prototypes' excellent Element.addMethods you can add this functionality fairly easily.

    lastDescendant: function(element) {
        element = $(element).lastChild;
        while (element && element.nodeType != 1) 
            element = element.previousSibling;
        return $(element);

After the code above is executed, you can use this new method as any other Element's method, either with var lastDesc = Element.lastDescendant(element); or var lastDesc = $(element).lastDescendant();.


This Tip is based on Diego Perini's post in lastDescendant enhancement thread of Prototype: Core mailing list.

rating: 0+x
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License