Treehouse: Grow your CSS skills. Land your dream job.

relative jquery selector?

  • # May 7, 2010 at 3:50 pm

    Hi folks, hopefully easy but I cant find the solution on the docs or with google…

    I am trying to select a div based on a class name, relative to "this"

    Here is what I need to do, the item that responds to the mouse event is at level 2, I need to move UP one level, and then select a different target within that DIV:

    However when I try and type this out, it throws an error:


    I realize this looks all wrong, but how can I do it?

    I can’t target the class name directly because it is shared by all items that are created in my grid, so I need to target an element only within my current grid [div] location.


    # May 14, 2010 at 8:31 pm

    Since you know you need to go two levels up, you can use positional selectors

    $(‘.someClass:eq(1)’) // selects the second element with a class name of someClass (yeah, it’s base 0)

    For your example you can use (note: using parents() rather than parent()):


    Which will find all parents of $(this), select the 2nd one, and hide it.

    # June 2, 2010 at 1:57 pm

    thanks, eq(1) works if the order of the divs is always going to be the same, but this is not a very good idea when thinking about scalability of a website and the potential for new properties/fields to be added to a site.

    Instead, I found out I could use:


    So I am calling the class name, not a relative sibling, which is what I needed. Yaay!

    # June 2, 2010 at 1:59 pm

    and Hi Joel!! This solution btw was provided by Ryan.

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.