Bug Tracker

Modify

Ticket #2047 (closed enhancement: worksforme)

Opened 5 years ago

Last modified 5 years ago

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:
Blocking: Blocked by:

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

comment:1 Changed 5 years ago by davidserduke

  • Status changed from new to closed
  • Resolution set to worksforme

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 5 years ago by phpmyforum

  • Status changed from closed to reopened
  • Resolution worksforme deleted

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 5 years ago by brandon

  • Status changed from reopened to closed
  • Resolution set to fixed

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 5 years ago by brandon

  • Status changed from closed to reopened
  • Resolution fixed deleted

comment:5 Changed 5 years ago by brandon

  • Status changed from reopened to closed
  • Resolution set to worksforme

Please follow the  bug reporting guidlines and use  jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

View

Add a comment

Modify Ticket

Action
as closed
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.