jquery
  1. jquery-nextall

jQuery nextAll()

The jQuery nextAll() method retrieves all the elements that come after the selected element.

Syntax

$(selector).nextAll(filter)
  • selector: Required. Specifies the element to retrieve the next siblings from.
  • filter: Optional. Specifies a selector to filter the next siblings.

Use

The nextAll() method is primarily used to retrieve all the following siblings of an element based on a given filter.

Example

Suppose we have a simple HTML list as follows:

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li class="active">Item 4</li>
    <li>Item 5</li>
</ul>

We can use the nextAll() method to select all the elements that come after the active <li> element:

$("li.active").nextAll().css("background-color", "yellow");

<!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>Item 2</li>
    <li>Item 3</li>
    <li class="active">Item 4</li>
    <li>Item 5</li>
</ul>

  <script>
$("li.active").nextAll().css("background-color", "yellow");
  </script>

</body>
</html>
Try Playground

In this example, we use the nextAll() method to select all the <li> elements that come after the active element and apply a yellow background to them.

Summary

The jQuery nextAll() method is used to retrieve all the siblings that come after the selected element based on a given filter. It can be used to select and manipulate elements in a more specific and efficient way.

Published on: