Selecting Specific Siblings - J Query

Problem
You need to select only a specific set of siblings of a particular element.

Solution

If you’re looking to select the adjacent sibling of a particular element, then you can use the adjacent sibling combinator (+). Similar to the child (>) combinator, the sibling combinator expects a selector expression on each side. The right hand expression is the subject of the selector, and the left hand expression is the sibling you want to match.Here’s some example HTML markup:

If you want to select only <h2>elements that immediately follow <h1>elements, you can use the following selector:

In this example, only one <h2>element will be selected (the first one). The second one is not selected because, while it is a sibling, it is not an adjacent sibling of the <h1>element.
If, on the other hand, you want to select and filter all siblings of an element, adjacent or not, then you can use jQuery’s siblings() method to target them, and you can pass an optional selector expression to filter the selection:

Sometimes you’ll want to target siblings dependent on their position relative to other elements; for example, here’s some typical HTML markup:

To select all list items beyond the second (after li.selected), you could use the following method:

The nextAll() method, just like siblings(), accepts a selector expression to filter theselection before it’s returned. If you don’t pass a selector, then nextAll() will return all siblings of the subject element that exist after the subject element, although not before it.
With the preceding example, you could also use another CSS combinator to select alllist items beyond the second. The general sibling combinator (~) was added in CSS3,so you probably haven’t been able to use it in your actual style sheets yet, but fortunately you can use it in jQuery without worrying about support, or lack thereof. It works inexactly the same fashion as the adjacent sibling combinator (+) except that it selects allsiblings that follow, not just the adjacent one. Using the previously specified markup,you would select all list items after li.selected with the following selector:

Discussion

The adjacent sibling combinator can be conceptually tricky to use because it doesn’t follow the top-down hierarchical approach of most other selector expressions. Still, it’s worth knowing about and is certainly a useful way of selecting what you want with minimal hassle.
The same functionality might be achieved without a selector, in the following way:

The next() method can make a nice alternative to the selector syntax, especially ina programmatic setting when you’re dealing with jQuery objects as variables, for example:


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics