Search code examples
jqueryparentrelative-pathchildren

jquery short hand for parent, children


i keep on having to affect elements relevant to other elements but my methods see a little amateur!

ie to

//  <div> <div> <div> <ul> matched item where script is called from </ul> </div> </div> <a class="postMore">LINK</a> </div>

i use;

$(this).parent('div').parent('div').parent('div').children('a.postMore').css('display','block');

which seems a little cumbersome. Is there a better way to handle relative elements?


Solution

  • There are multiple ways to traverse the DOM with jQuery, so you just need to identify the pattern in your html structure, and use the most relevant methods.

    In your example this should do what you want and it allows for much more flexibility.

    $(this).closest('div:has(a.postMore)').find('a.postMore');
    

    demo http://jsfiddle.net/gaby/j2Wgv/


    • .closest() will go upwards the DOM until if finds an elements that matches the selector we passed it as an argument.
    • Our selector is div:has(a.postMore) which means a div that contains a link with class postMore
    • And then we use the .find() to reach the actual link.