JQuery Sibling Selectors Tutorial 🎯

beginner
12 min

JQuery Sibling Selectors Tutorial 🎯

Welcome to our comprehensive guide on JQuery Sibling Selectors! In this tutorial, we'll learn how to select and manipulate elements that share the same parent as another selected element. This tutorial is perfect for both beginners and intermediate learners. Let's dive right in!

Understanding Sibling Selectors 📝

In HTML, siblings are elements that share the same parent. For instance, consider the following markup:

html
<div id="parent"> <p>First sibling</p> <p>Second sibling</p> <p>Third sibling</p> </div>

In the example above, <p> elements are siblings because they all have the same parent #parent.

JQuery Sibling Selectors 💡

JQuery provides several sibling selectors to help you navigate through siblings more efficiently. Let's explore the main sibling selectors:

  1. Next Sibling Selector (.next()): This selector selects the next sibling element after the selected element.

  2. Prev Sibling Selector (.prev()): This selector selects the previous sibling element before the selected element.

  3. Next All Sibling Selector (.nextAll()): This selector selects all the following siblings of the selected element.

  4. Prev All Sibling Selector (.prevAll()): This selector selects all the preceding siblings of the selected element.

  5. Next Until Selector (.nextUntil()): This selector selects all the following siblings up to, but not including, the sibling that matches the provided selector.

  6. Prev Until Selector (.prevUntil()): This selector selects all the preceding siblings up to, but not including, the sibling that matches the provided selector.

Practical Examples ✅

Let's practice by using some practical examples. We'll work with the following HTML markup:

html
<div id="parent"> <p id="first">First sibling</p> <p id="second">Second sibling</p> <p id="third">Third sibling</p> </div>

Example 1: Next Sibling Selector (.next())

javascript
$(document).ready(function() { $("#first").click(function() { $("#first").hide(); // hide the first sibling $("#second").show(); // show the second sibling }); });

In this example, when you click on the first sibling, it will hide itself and show the second sibling.

Example 2: Next All Sibling Selector (.nextAll())

javascript
$(document).ready(function() { $("#first").click(function() { $("#first").hide(); // hide the first sibling $("#parent").find("p").each(function() { $(this).toggle(); // toggle visibility for all the following siblings }); }); });

In this example, when you click on the first sibling, it will hide itself and toggle the visibility for all the following siblings.

Quiz Time 💡

Quick Quiz
Question 1 of 1

What does the `.next()` selector in JQuery do?

That's it for this tutorial! With practice, you'll be able to master sibling selectors and make the most out of JQuery in your projects. Stay tuned for more JQuery tutorials here at CodeYourCraft! 🎉