Bug Tracker

Opened 12 years ago

Closed 12 years ago

#2047 closed enhancement (worksforme)

better parent function (Prototype "up" like)

Reported by: phpmyforum Owned by:
Priority: minor Milestone: 1.2.2
Component: core Version: 1.2.1
Keywords: Cc:
Blocked by: Blocking:

Description

I often need a specific parent element instead of all or the direct parent, so I came up with this function:

$.fn.extend({
    //### Prototype "up" method
    up: function(selector)
    {
        var found = "";
        selector = $.trim(selector || "");

        $(this).parents().each(function()
        {
            if (selector.length == 0 || $(this).is(selector))
            {
                found = this;
                return false;
            }
        });

        return $(found);
    }
});

Change History (5)

comment:1 Changed 12 years ago by davidserduke

Resolution: worksforme
Status: newclosed

Is this different from :

$(this).parents(selector);

?

http://docs.jquery.com/Traversing/parents#expr

If I'm missing something about how yours differs please feel free to reopen the ticket and let me know.

comment:2 Changed 12 years ago by phpmyforum

Resolution: worksforme
Status: closedreopened

This is the difference:

$(this).parents(selector);

-> returns a set of all ancestors

$(this).up(selector);

-> returns just the first matched element

It behaves similar to prototype's up method (http://prototypejs.org/api/element/up), except you can't pass a number. Though this could also be added.

comment:3 Changed 12 years ago by brandon

Resolution: fixed
Status: reopenedclosed

Just add the :first selector to your selector. Then it will return what you want. You can also use :eq, :gt or :lt.

Here are the docs for the selectors: http://docs.jquery.com/Selectors

comment:4 Changed 12 years ago by brandon

Resolution: fixed
Status: closedreopened

comment:5 Changed 12 years ago by brandon

Resolution: worksforme
Status: reopenedclosed
Note: See TracTickets for help on using tickets.