How to use jquery next() to select next div by class

前端 未结 2 1616
南方客
南方客 2021-02-18 16:09

I\'m fairly new to jquery and struggling with something that should be fairly simple. I want to select the previous and next div with class \"MenuItem\" from the div with class

2条回答
  •  孤独总比滥情好
    2021-02-18 17:10

    Have you tried:

    $('div.MenuItemSelected').nextAll('.MenuItem:first');
    

    I think the problem you are facing is that next returns the very next sibling, whereas nextAll returns a collection of all the subsequent siblings matching your selector. Applying the :first selector to your nextAll filter should make things right.

    I would like to point out, that if the structure of your markup is consistent (so it's always guaranteed to work), then your current solution might (benchmark, benchmark, benchmark) well be the faster way:

    $('div.MenuItemSelected').next().next();
    

提交回复
热议问题