过滤就是从匹配元素集合中找到想要的元素。(就是从一堆元素中找我们想要的那些)
1.first()和last()
语法:$(selector).first()
获取匹配元素集合中第一个元素。这个方法不接受任何参数。
语法:$(selector).last()
获取匹配元素集合中最后一个元素。这个方法不接受任何参数。
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
</ul>
<p>
<span>Look:</span>
<span>This is some text in a paragraph.</span>
<span>This is a note about it.</span>
</p>
<script>
$("li").first().css("background-color", "red");
$("p span").first().addClass('highlight');
</script>
2.filter()和not()和has()
filter: 把需要的过滤出来
not: filter的反义词,把不需要的过滤出来
has:包含
<ul id="list">
<li> <span class="a">我是span</span> 111111</li>
<li class="a">2222222</li>
<li>33333333</li>
<li class="b">4444444</li>
<li class="a">5555555555</li>
</ul>
<script>
// $("#list li").css("background-color",'red'); // 所有li都会变
// $("#list li").filter('.a').css("background-color",'red'); // 带.a的li会
// $("#list li").not('.a').css("background-color",'red'); // 不带.a的li
$("#list li").has('.a').css("background-color",'red'); // 子元素中有带.a的li
</script>
3.eq()
下标从0开始
<h1>我是标题00000</h1>
<div class="box">
<p>111111</p>
<p>2222</p>
<div>
<p>333</p>
</div>
<p class="selected">444444</p>
<h1>我是标题1111</h1>
</div>
<script>
$("h1").eq(1).css('color','blue')
$(".box").find("p").eq(3).css('color','red')
</script>
4.index()方法
索引就是当前元素在所有兄弟节点中的位置,从0开始(就是当前元素在一组元素中的位置,当前元素和这一组元素是平级的兄弟关系)
<div>
<h1>11111</h1>
<h2>222222222</h2>
<h1>333333333</h1>
<h2 id="hhh">444444444444</h2>
<h1>555555555555</h1>
<p>666666666</p>
</div>
<h2>7777777777</h2>
<script>
$(function(){
alert($('#hhh').index()); // 3
});
</script>