您的位置:首页 > Web前端 > JQuery

jQuery -> 获取兄弟元素

2014-05-22 17:05 405 查看
获取指定元素的兄弟元素时,可以使用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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: