Page Content

Tutorials

What are the Prev Siblings in jQuery with Code Example

Prev Siblings in jQuery

A strong tool in jQuery for choosing elements that are siblings of a given element that come after it in the HTML structure is the prior ~ siblings selector, also called the generic sibling combinator. Instead of focussing on the immediate sibling or all siblings, regardless of location, you can target any subsequent sibling elements that fit a given pattern.

Syntax:

A ~ B
  • A: Stands for the sibling element that comes before it, which serves as the selection’s reference point.
  • The generic sibling combinator requires B to follow A and be its sibling.
  • In the document structure, B stands for the elements that are siblings of A and come after A.

How it Works

jQuery initially finds all elements that match the A component of the selector when it comes across an A ~ B selector. It next looks through every subsequent sibling element elements that occur later in the HTML and share the same direct parent for every matching A element. The final set of selected items includes these siblings if they meet the selector’s B component.

jQuery DOM traversal and CSS selectors simplify component identification. The DOM creates a web page tree by defining relationships between parents, children, and siblings. Despite browser incompatibilities in plain JavaScript, JQuery provides a sophisticated and reliable means to deal with this structure.

Understanding how the ~ combinator differs from other sibling-related selectors and techniques is useful:

Adjacent Sibling Combinator (A + B): This only chooses A’s sibling that is immediately adjacent to B. A element would only be chosen by strong + em, for instance, if it comes right after a sibling element. Because it doesn’t require immediate adjacency, the ~ combinator is more broad.

.next([selector]) method: The jQuery function.next([selector]) retrieves each matching element’s distinct next sibling, optionally filtered. Although it is a method applied to a jQuery object rather than a selector string, it is comparable to A + B.

.nextAll([selector]) function: This approach, which may be filtered by a selector, identifies all sibling elements after the current element. While it is contained within the selector string itself, the A ~ B selector selects all of the siblings that follow in a similar manner.

The methods.prevAll([selector]) and.prev([selector]): Although they choose prior siblings, these are the equivalents of.next() and.nextAll(), respectively.

.siblings([selector]) method: Regardless of whether they appear before or after the current element, this method picks all additional elements that are at the same DOM level as it. Particularly, the ~ combinator concentrates on following siblings.


Similar to other jQuery selectors, the A ~ B selector permits implicit iteration, which enables methods like addClass() or hide() to be applied to the full set after elements have been chosen without requiring the creation of explicit loops. This speeds up site development and drastically reduces code length.

Code Example:

A sample of code Let’s see how the p ~ span and p ~ ul selectors operate. The p ~ ul selector in HTML targets elements that are siblings of elements. Likewise, p ~ span would target components that come after a sibling.

<!DOCTYPE html>
<html>
<head>
  <title>jQuery ~ Sibling Selector</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <style>
    .highlight { background-color: yellow; }
    .underline { text-decoration: underline; color: blue; }
  </style>
</head>
<body>
  <h3>Sibling Selector Demo</h3>
  <p>First paragraph</p>
  <span>This span comes after the paragraph</span>
  <p>Second paragraph</p>
  <p>Third paragraph</p>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
  </ul>
  <button id="applyEffect">Highlight</button>
  <script>
    $(document).ready(function() {
      // Select span that is a sibling after p
      $("p ~ span").addClass("highlight");
      $("#applyEffect").click(function() {
        // Select p elements that are siblings after another p
        $("p ~ p").addClass("underline");
      });
    });
  </script>
</body>
</html>

Output:

Sibling Selector Demo
First paragraph
This span comes after the paragraph
Second paragraph
Third paragraph
•	Item 1
•	Item 2
Highlight

Explanation of the Code Example

HTML Structure:

  • There are two div elements (container1 and container2) in the HTML document that function as separate sections. To establish distinct sibling connections, these sections contain nested elements like as h2, p, ul, and span.
  • The code links to jQuery via a CDN. The entire jQuery script is in $(document).ready(function() {… }); to prevent JavaScript code from running until the browser fully loads and parses the DOM. This prevents script errors when working with uncreated items.

$(“p ~ ul”).addClass(“styled-list”):

  • This line makes use of the p ul selector. To detect siblings of a element, jQuery locates all elements after it in the HTML structure.
  • Since it is a sibling, the following the first will be chosen.
  • After the second (after the ), the will be chosen for the same reason.
  • The first will not be selected as there is no sibling before it.
  • The element following the will be selected.
  • Apply the “styled-list” CSS class to all elements that match the selection, bolding and bordering the text blue. This shows how jQuery allows dynamic web page styling and appearance change.

$(“p ~ span”).addClass(“highlight”):

  • The p span selector is used in this line. jQuery locates all elements that are siblings to a element using this command.
  • The element follows the second element. Thus, the will be selected and given the highlight class, creating a yellow background.
  • This particular p ~ span criterion is not met by any elements in container2.
  • To identify focused elements in jQuery examples, the highlight class is often utilised.

$(“p ~ p”).addClass(“underlined”):

  • When the user selects the “Apply Underline to p ~ p” button, this section of code is run.
  • The selector p ~ p targets siblings of elements that appear after the previous one.
  • The initial is followed by the second one. Someone will choose it.
  • The second is followed by the third. Someone will choose it.
  • The third is followed by the fourth. Someone will choose it.
  • This rule will not choose the paragraph in container 2 since it is not preceded by another sibling within the same direct parent div.
  • The matching paragraphs’ content is subsequently underlined when the addClass(“underlined”) method applies the underlined CSS class to them.

This example demonstrates the clear control that jQuery’s ~ (generic sibling combinator) selector offers, allowing developers to quickly and effectively choose items based on their relational location to other siblings. Having this capacity is essential for building dynamic, rich web front ends.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index