next

next(element[, cssRule][, index = 0]) -> HTMLElement | undefined

Returns element’s following sibling (or the index’th one, if index is specified) that matches cssRule. If no cssRule is provided, all following siblings are considered. If no following sibling matches these criteria, undefined is returned.

The Element.next method is part of Prototype’s ultimate DOM traversal toolkit (check out Element.up, Element.down and Element.previous for some more Prototypish niceness). It allows precise index-based and/or CSS rule-based selection of any of element’s following siblings. (Note that two elements are considered siblings if they have the same parent, so for example, the head and body elements are siblings—their parent is the html element.)

As it totally ignores text nodes (it only returns elements), you don’t have to worry about whitespace-only nodes.

And as an added bonus, all elements returned are already extended allowing chaining:


$(element).down(1).next('li', 2).hide();

Walking the DOM has never been that easy!

Arguments

If no argument is passed, element’s following sibling is returned (this is similar as calling nextSibling except Element.next returns an already extended element).

If an index is passed, element’s corresponding following sibling is returned. (This is equivalent to selecting an element from the array of elements returned by the method Element.nextSiblings). Note that the sibling right below element has an index of 0.

If cssRule is defined, Element.next will return the element first following sibling that matches it.

If both cssRule and index are defined, Element.next will collect all of element’s following siblings matching the given CSS rule and will return the one specified by the index.

In all of the above cases, if no following sibling is found, undefined will be returned.

Examples


<ul id="fruits">
  <li id="apples">
    <h3 id="title">Apples</h3>
    <ul id="list-of-apples">
      <li id="golden-delicious">Golden Delicious</li>
      <li id="mutsu">Mutsu</li>
      <li id="mcintosh" class="yummy">McIntosh</li>
      <li id="ida-red" class="yummy">Ida Red</li>
    </ul>
    <p id="saying">An apple a day keeps the doctor away.</p>  
  </li>
</ul>

$('list-of-apples').next();
// equivalent:
$('list-of-apples').next(0);
// -> p#sayings

$('title').next(1);
// -> ul#list-of-apples

$('title').next('p');
// -> p#sayings

$('golden-delicious').next('.yummy');
// -> li#mcintosh

$('golden-delicious').next('.yummy', 1);
// -> li#ida-red

$('ida-red').next();
// -> undefined