jQuery to get next match in the DOM after a particular element

浪子不回头ぞ 提交于 2019-12-05 08:46:01

Inside the click handler, try this:

Example: http://jsfiddle.net/QVphP/ (click a blue box to add a border to the next one)

var $foo = $('img.foo');  // get all .foo images

var idx = $foo.index( this );  // get the index position of "this"
                               //    relative to all the .foo images found

var next = $foo.eq( idx + 1 ); // grab the .foo for the incremented index

Check out next. It does exactly what you want.

$('img.foo').next().css('background-color', 'red');

If you'd like to get all the items after your currently selected item AND you know what position it is in your DOM, you can use the gt selector to select all the items "greater than" itself.

For example:

$('img.foo:gt(4)')

would give you back all of the items that are "greater than" the 4th item in the selection (AKA, after and not the current one).

Check out this jsfiddle. Click any image with a red border (foo) and the next red border (the next foo) will change to yellow.

Depending on how many foos you have in the page, this solution could be a bit of a performance hit. But since you aren't on 1.4 yet, this will work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!