jquery
  1. jquery-prevuntil

jQuery prevUntil()

The jQuery prevUntil() function is used to select all the preceding siblings of an element until another element is encountered.

Syntax

The syntax for prevUntil() function is as follows:

$(selector).prevUntil(selector, filter);
  • selector: Specifies the element(s) to stop selection. The selection will stop at this point. Optional.
  • filter: Specifies a filter function to display specific elements. Optional.

Use

The prevUntil() method is useful when you need to select a range of elements preceding an element. For example, you might want to select all the table cells above a specific checkbox, but you don't know exactly how many cells there are. prevUntil() can be used to specify the stopping point for the selection.

Example

Consider the following HTML code:

<div class="container">
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <p class="selected">Paragraph 3</p>
  <p>Paragraph 4</p>
  <p>Paragraph 5</p>
</div>

The following jQuery code will select all the p elements preceding .selected until the first p element is encountered:

$(".selected").prevUntil("p:first").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>
<div class="container">
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <p class="selected">Paragraph 3</p>
  <p>Paragraph 4</p>
  <p>Paragraph 5</p>
</div>


    <script>
$(".selected").prevUntil("p:first").css("color", "red");



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

This will select all the p elements above .selected except for the first p, and apply the style color: red to them.

Summary

The prevUntil() method in jQuery is a powerful tool for selecting elements that appear before a specific element, up to a specified stopping point. Whether you need to select all the table cells preceding a particular checkbox or simply want to change the styling of a range of elements, prevUntil() can help you achieve your goal with minimal effort.

Published on: