一般情况下不会单独使用,和其他基本选择器组合使用,在现有的基础上再进行筛选过滤,使得选择更加精准,因此个人认为称作过滤器好一些,主要有两个系列,一个是child系列,一个是type系列,第二个比较常用
child系列主要有以下过滤器:
:first-child
:last-child
:nth-child(n | even | odd | formula)
:nth-last-child(n | even | odd | formula)
:only-child
特点:
- 语义化,如:first-child 第一个子节点
- child类型更偏向于先选择子节点,再判断其是什么类型。
- 可获取参数类型多
- n 匹配元素序号,必须为整数,从1开始
- even 匹配所有偶数元素
- odd匹配所有奇数元素
- formula 使用特殊公式例如(an+b)进行选择
:first-child
例如:
$('details > p:first-child') //details标签下第一个必须是p标签才会被选择;
:last-child
例如:
$('details > p:last-child') //details标签下最后一个必须是p标签才会被选择;
:nth-child(n | even | odd | formula)
例如:
$('details > p:nth-child(2)') //details标签下第二个必须是p标签才会被选择;
- ()内的数字是从1开始算的,下同
:nth-last-child(n | even | odd | formula)
例如:
$('details > p:nth-last-child(2)') //details标签下倒数第二个必须为p标签才会被选择;
:only-child
例如:
$('details > p:only-child') //details标签下第一个必须只有一个子标签并且为p标签才会被选择;
type系列主要有以下过滤器:
:first-of-type
:last-of-type
:nth-of-type (n | even | odd | formula)
:nth-of-type (n | even | odd | formula)
:only-of-type
其用法与child一致
特点:
- 语义化,如:first-of-type 第一个节点类型
- type类型更偏向于先确定节点类型,再把符合条件的该类型的节点返回。
- 可获取参数类型多,同child类型
child系列与type系列的区别
- child系列更偏向于子代,以代为基准,例如details > p:first-child必须是该元素下子节点顺序第一个p标签才能被选择。
- type类型更偏向于类型,以类型为基准,例如details > p:first-of-type会先将details下的所有p标签获取,再返回其第一个。
- 相对来说type类型更自由,不需要去考虑其是子代下第几个,因此在使用时更喜欢用。
- 个人认为child系列偏向广度优先,而type系列偏向深度优先,因为在相同时间内,获取某代第几个节点比type系列全部获取再返回第几个速度要快。