.nextUntil()

.nextUntil( [ selector ] ) Returns: jQuery

Description: Get all following siblings of each element up to but not including the element matched by the selector.

  • version added: 1.4.nextUntil( [ selector ] )

    selectorA string containing a selector expression to indicate where to stop matching following sibling elements.

Given a jQuery object that represents a set of DOM elements, the .nextUntil() method allows us to search through the successors of these elements in the DOM tree, stopping when it reaches an element matched by the method's argument. The new jQuery object that is returned contains all following siblings up to but not including the one matched by the .nextUntil() selector.

If the selector is not matched or is not supplied, all following siblings will be selected; in these cases it selects the same elements as the .nextAll() method does when no filter selector is provided.

Consider a page with a simple definition list as follows:

<dl>
  <dt>term 1</dt>
  <dd>definition 1-a</dd>
  <dd>definition 1-b</dd>
  <dd>definition 1-c</dd>
  <dd>definition 1-d</dd>

  <dt id="term-2">term 2</dt>
  <dd>definition 2-a</dd>
  <dd>definition 2-b</dd>
  <dd>definition 2-c</dd>

  <dt>term 3</dt>
  <dd>definition 3-a</dd>
  <dd>definition 3-b</dd>
</dl>

If we begin at the second term, we can find the elements which come after it until a following <dt>.

$('#term-2').nextUntil('dt').css('background-color', 'red');

The result of this call is a red background behind definitions 2-a, 2-b, and 2-c.

Example:

Find the siblings that follow <dt id="term-2"> up to the next <dt> and give them a red background color.

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	<dl>
  <dt>term 1</dt>
  <dd>definition 1-a</dd>
  <dd>definition 1-b</dd>
  <dd>definition 1-c</dd>
  <dd>definition 1-d</dd>

  <dt id="term-2">term 2</dt>
  <dd>definition 2-a</dd>
  <dd>definition 2-b</dd>
  <dd>definition 2-c</dd>

  <dt>term 3</dt>
  <dd>definition 3-a</dd>
  <dd>definition 3-b</dd>
</dl>
<script>
    $("#term-2").nextUntil("dt")
      .css("background-color", "red")
</script>
</body>
</html>

Demo: