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?
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 adiv
that contains a link with classpostMore
- And then we use the
.find()
to reach the actual link.
You can use .closest()
which will search upwards through the DOM tree. So if you give your div that contains a.postMore
a class, you can use $(this).closest('class').children('a.postMore')
.
Documentation here
精彩评论