开发者

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 a div that contains a link with class postMore
  • 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜