This article mainly introduces several good methods for jQuery to obtain sibling elements. If you need a friend, you can use adjacent sibling combinator (+) to obtain sibling elements of a specified element ), both sides of + are selector expressions.
If you want to obtain the direct brother element h2 of all h1 in the following example
The Code is as follows:
Main title
Section title
Some content...
Section title
More content...
Can be used directly
The Code is as follows:
$('H1 + h2 ')
// Select ALL h2 elements that are adjacent siblings of H1 elements.
If you want to filter out the sibling elements of h1, you can also use
The Code is as follows:
$('H1 '). siblings ('h2, h3, p ');
// Select all H2, H3, and P elements that are siblings of H1 elements.
To obtain all the sibling elements after the current element, you can use nextAll ()
For example, for the following html code
The Code is as follows:
- First item
- Second Item
- Third item
- Fourth item
- Th item
To obtain all the li elements after the second entry, use the following code:
The Code is as follows:
$ ('Li. selected'). nextAll ('lil ');
In the preceding example, general sibling combinator (~) can also be used (~) To achieve
The Code is as follows:
$ ('Li. selected ~ Li ');
You can directly use next () without using selector to obtain the direct sibling element ().
The Code is as follows:
Var topHeaders = $('h1 ');
Topheaders.next('h2'hangzhou.css ('margin ', '0 );