jquery
  1. jquery-nextuntil

jQuery nextUntil()

The jQuery nextUntil() method is used to select all the following siblings of an element until the specified selector. Let's take a closer look at the syntax, use, and examples of nextUntil().

Syntax

$(selector).nextUntil(filter)

The selector parameter represents the element to start searching for, while the filter parameter represents the element to stop searching for.

Use

The nextUntil() method is useful when you want to select a range of elements that come after a specific element. It can be used to select multiple siblings, or to select a range of elements within a specific section of your web page.

Example

Let's say we have the following HTML code:

<ul>
    <li>Item 1</li>
    <li class="selected">Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
    <li>Item 8</li>
</ul>

We can use the nextUntil() method to select all the following siblings of the li element with class selected until the li element with the class active, like this:

$("li.selected").nextUntil("li.active").css("color", "red");

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jQuery Example</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  <style>
  
  </style>
</head>
<body>

<ul>
    <li>Item 1</li>
    <li class="selected">Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
    <li>Item 8</li>
</ul>


  <script>
$("li.selected").nextUntil("li.active").css("color", "red");

  </script>

</body>
</html>
Try Playground

This code will select all the elements between li.selected and li.active and change the text color to red.

Summary

nextUntil() is a useful jQuery method that can be used to select a range of elements that come after a specific element. It's great for selecting multiple siblings or a range of elements within a section of your web page. Try it out in your project!

Published on: