Be careful about closest(), as if it doesn't find any matches it will
return the element itself.

The alternative is $(this).parents("form:first")

Essentially, parent() returns the parent (the one and only) and then
filters it to the selector you gave. parents() does the same but with
all parents, in order, up to <body>.

$(this).parent().parent().prev().prev().prev().children("p.example")

could be turned into

$(this).parents('.myTarget').prevAll('.myOtherTarget').children
("p.example");

but neither is good, you shouldn't have the need for this kind of long
traversal.

- ricardo

On Jan 28, 4:01 pm, jay <jay.ab...@gmail.com> wrote:
> parent is just one level.  closest() looks up the tree like .parent
> ().parent()... until a match is found.. I'm not sure if there is an
> equivalent that would do what you want.. you could try .closest
> (".parentClass").find(".childClass")
>
> On Jan 28, 12:53 pm, kgosser <kgos...@gmail.com> wrote:
>
> > No, not necessarily, but thanks for the link. I'll take a deeper look
> > at that.
>
> > What my question centers around is when I put parent("example"); ...
> > how far up the tree does jQuery look for the "example" -- just one
> > level, or higher?
>
> > The key is I'm trying to understand how to stop having to write
> > traversing like this:
>
> > $(this).parent.().parent().prev().prev().prev().children("p.example");
>
> > If you see what I'm getting at?
>
> > On Jan 28, 11:42 am, jay <jay.ab...@gmail.com> wrote:
>
> > >http://docs.jquery.com/Traversing/closest
>
> > > On Jan 28, 12:39 pm, kgosser <kgos...@gmail.com> wrote:
>
> > > > Hello, pretty noob question here. I have this example:
>
> > > > <div>
> > > >    <form>
> > > >       <div>
> > > >           <label>Example</label>
> > > >           <input type="text"/>
> > > >       </div>
> > > >    </form>
> > > > </div>
>
> > > > Now let's say there's this jQuery:
>
> > > > $("input").click(function(){
> > > >    $(this).parent("form").css("color","#F00");
>
> > > > });
>
> > > > My question: Does the parent() method work like that, or do I need to
> > > > do something like $(this).prev().prev() to get to the form? I guess
> > > > I'm trying to better understand how flexible the parent() and children
> > > > () methods are.
>
> > > > Thanks in advance.- Hide quoted text -
>
> > - Show quoted text -

Reply via email to