jQuery -> 获取兄弟元�

获取指定元素的兄弟元素时,能够使用adjacent sibling combinator (+),当中+的两側内容都是selector expression.
假设要获取下例中全部的 h1的直接兄弟元素h2
<div>
    <h1>Main title</h1>
    <h2>Section title</h2>
    <p>Some content...</p>
    <h2>Section title</h2>
    <p>More content...</p>
</div>

能够直接使用
$('h1 + h2') 
  // Select ALL h2 elements that are adjacent siblings of H1 elements.

假设要过滤h1的兄弟元素,当然也能够使用
$('h1').siblings('h2,h3,p');
  // Select all H2, H3, and P elements that are siblings of H1 elements.

假设要获取当前元素之后的全部兄弟元素,能够使用nextAll()
比如,针对以下的html代码
<ul>
    <li>First item</li>
    <li class="selected">Second Item</li>
    <li>Third item</li>
    <li>Fourth item</li>
    <li>Fifth item</li>
</ul>
假设要获取第二个条目之后的全部li元素,能够使用例如以下代码
$('li.selected').nextAll('li');
上例也能够使用general sibling combinator (~)来实现
$('li.selected ~ li');

获取直接兄弟元素也能够不使用selector,直接使用next()
var topHeaders = $('h1');
topHeaders.next('h2').css('margin', '0);
原文地址:https://www.cnblogs.com/yxwkf/p/3875772.html