JQuery is a good way to get sibling elements

  • 2020-03-30 03:03:27
  • OfStack

When you get a sibling of a specified element, you can use the adjacent sibling combinator (+), where both sides of the + are selector expressions.
If you want to get all of the h1's direct sibling h2 in the following example
<h1>Main title</h1> 
<h2>Section title</h2> 
<p>Some content...</p> 
<h2>Section title</h2> 
<p>More content...</p> 

Can be used directly
$('h1 + h2') 
// Select ALL h2 elements that are adjacent siblings of H1 elements. 

If you want to filter h1's sibling elements, you can also use it
// Select all H2, H3, and P elements that are siblings of H1 elements. 

To get all sibling elements after the current element, use nextAll()
For example, for the following HTML code
<li>First item</li> 
<li class="selected">Second Item</li> 
<li>Third item</li> 
<li>Fourth item</li> 
<li>Fifth item</li> 

If you want to get all the li elements after the second entry, you can use the following code

The above example can also be implemented using general sibling combinator (~)
$('li.selected ~ li'); 

You can also get a direct sibling element by using next() without using selector.
var topHeaders = $('h1'); 
topHeaders.next('h2').css('margin', '0); 

Related articles: