How can we target specific sibling elements?

Question

In the context of this exercise, the .siblings() method returns all siblings of an element, but how can we target specific sibling elements?

Answer

There are a few ways you can target specific sibling elements when utilizing the .children() function.

One way is to pass in a selector, like a class name, such that only the siblings that match it will be returned. For example, the following will only return sibling elements with the class “target-class”.

$("li").siblings(".target-class");

Another way you can target specific sibling elements is by selecting them one at a time, by index from the jQuery object containing all the siblings. For example, given the HTML code,

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

We could select the first and last sibling elements by doing the following,

var siblings = $(".target").siblings();

console.log(siblings[0]); // <li>Item 1</li>
console.log(siblings[2]); // <li>Item 4</li>
5 Likes

console.log(siblings[2]); // <li>Item 3</li>

1 Like

That’s incorrect. You’re thinking of the index if all of the <li>s were included. Here’s how the counting works in the example given above:

Sibling 0:     <li>Item 1</li>
Not a sibling: <li class="target">Item 2</li>
Sibling 1:     <li>Item 3</li>
Sibling 2:     <li>Item 4</li>
1 Like