jQuery: get immediate next element after the current element

ravikiran picture ravikiran · Sep 11, 2009 · Viewed 55k times · Source

I need set focus to the element that is immediate next(and in other case immediate prev ) to the current element.

For example:

<li>item1</li> <- prev element (get this element)
<li>item1</li><- current element
<li>item1</li> <- next element (get this element)
<li>item1</li>

This is what I used

var curr = (event.target).next();
$(curr).trigger('focus');

when I check the value of curr in firebug it shows undefined for some reason.

Answer

geowa4 picture geowa4 · Sep 11, 2009

Use

$(event.target).next() 

to get the next sibling. You can also pass an expression to the next function. This will select the next sibling to match you selector:

$(event.target).next("p")

You can also use nextAll, which works the same way but returns all of the following sublings. See more here. There is also, prev and prevAll, which are the analogues for getting the previous element(s).

Basically, you were really close, you just need to wrap event.target in the jQuery object, as event.target returns the actual element.