jQuery使用(四):DOM操作之查找兄弟元素和父级元素
查找兄弟元素
向下查找兄弟元素
- next()
- nextAll()
- nextUntil()
向上查找兄弟元素
- prev()
- prevAll()
- prevUntil()
查找所有兄弟元素
- siblings()
1.1.1.next()方法用来查找下一个兄弟元素,可以传参也可以不传参。参数可以是任意jQuery选择器,表示如果下一个元素如果是指定的元素就选定。当没有选中指定的元素时,jQuery链式调用还是保持原来的jQuery对象。
<!-- next --> <button>点我</button> <span class="demo">duyi-cst</span> <p class="demo">duyi-cst</p>
示例:
$('button').click(function(){ $(this).next().css({fontSize:'20px',color:'orange'}); console.log( $(this).next('span') );//可以选中元素span console.log( $(this).next('p') );//不能选中元素p,jQuery链式调用还是保持button的jQuery对象 });
1.1.2nextAll()方法用来查找下面所有兄弟元素,可以传参也可以不传参。参数可以是任意jQuery选择器,表示如果同级后面的元素如果是指定的元素就选定。当没有选中指定元素时,jQuery链式调用还是保持原来的jQuery对象。
<div class="wrapper"> 全选:<input type="checkbox"></input> banana:<input type="checkbox" name=""> apple:<input type="checkbox" name=""> orange:<input type="checkbox" name=""> <input type="submit" value="login" name=""></input> </div>
示例:使用nextAll()通过全选按钮获取后面的所有复选框,并实现全选和全部撤销功能
$('input[type="checkbox"]').eq(0).click(function(){ if( $(this).prop('checked') ){ $(this).nextAll('input[type="checkbox"]').prop('checked',true); }else{ $(this).nextAll('input[type="checkbox"]').prop('checked',false); } });
1.1.3.nextUntil()方法用来查找下面所有兄弟元素,可以传入两个参数,第一个参数指定结束位置,第二个参数指定选择的元素;参数可以是任意jQuery选择器。
//html代码 <div class="wrapper1"> <h1>水果</h1> 全选:<input type="checkbox"></input> banana:<input type="checkbox"> apple:<input type="checkbox"> orange:<input type="checkbox"> <h1>nba</h1> 全选:<input type="checkbox"></input> Rose:<input type="checkbox"> Curry:<input type="checkbox"> James:<input type="checkbox"> <input type="button" value="submit"> </div> //js代码 $('.wrapper1 h1').next().click(function(){ if( $(this).prop('checked') ){ $(this).nextUntil('h1','input[type="checkbox"]').prop('checked',true); }else{ $(this).nextUntil('h1','input[type="checkbox"]').prop('checked',false); } });
1.2.1.prev()方法用来查找上一个兄弟元素,可以传参也可以不传参。参数可以是任意jQuery选择器,表示如果上一个元素如果是指定的元素就选定。当没有选中指定的元素时,jQuery链式调用还是保持原来的jQuery对象。
<span class="demo">duyi-cst</span> <p class="demo">duyi-cst</p> <button>点我</button>