treehouse : what would you like to learn today?
Web Design Web Development iOS Development

relative jquery selector?

  • 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:

    $(this).parent().('.views-field-field-image-fid').hide();


    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.

    Thanks!!
  • 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()):

    $(this).parents().eq(1).hide();


    Which will find all parents of $(this), select the 2nd one, and hide it.
  • 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:

    $(this).siblings(\".views-field-nid\").show();


    So I am calling the class name, not a relative sibling, which is what I needed. Yaay!
  • and Hi Joel!! This solution btw was provided by Ryan.