jquery
  1. jquery-prevall

jQuery prevAll() Method

The jQuery prevAll() method finds all the siblings of an element that appear before it in the HTML structure and returns them in a jQuery object.

Syntax

$(selector).prevAll(filter)
  • selector - Required. The selector that identifies the element whose previous siblings to select.
  • filter - Optional. A selector that can be used to filter the selected siblings.

Use

The prevAll() method is useful for selecting all the previous siblings of an element that match a given selector. This can be helpful when you need to operate on a set of elements that appear before the current element in the DOM hierarchy.

Example

Consider the following HTML structure:

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

If we want to select all the previous siblings of the currently selected item using the prevAll() method, we can use the following jQuery code:

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


<!DOCTYPE html>
<html>
<head>
    <title>jQuery parent() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
</head>
<body>
  <ul>
  <li>Item 1</li>
  <li class="selected">Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>

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


    </script>
</body>
</html>
Try Playground

This code will select all the previous siblings of the li element with class selected, which in this case is Item 1, and Item 2. The .css() method is then used to change the text color to red for these selected siblings.

Summary

The prevAll() method in jQuery is a useful tool for selecting the previous siblings of an element that match a given selector. It makes it easy to operate on a set of elements that appear before the current element in the DOM hierarchy. Use it whenever you need to select multiple elements that appear before the current element.

Published on: