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
 
<div> 
<h1>Main title</h1> 
<h2>Section title</h2> 
<p>Some content...</p> 
<h2>Section title</h2> 
<p>More content...</p> 
</div> 

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
 
$('h1').siblings('h2,h3,p'); 
// 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
 
<ul> 
<li>First item</li> 
<li class="selected">Second Item</li> 
<li>Third item</li> 
<li>Fourth item</li> 
<li>Fifth item</li> 
</ul> 

If you want to get all the li elements after the second entry, you can use the following code
 
$('li.selected').nextAll('li'); 

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: