Sizzle 强大 DOM 选择器引擎 jQuery 默认选择器引擎 - 文章教程

Sizzle 强大 DOM 选择器引擎 jQuery 默认选择器引擎

发布于 2018-11-08 字数 13497 浏览 1778 评论 0

jQuery 从 1.3 版本开始,使用了新的选择器引擎 Sizzle,官方网址。Sizzle 是 jQuery 作者 John Resig 开发的 DOM 选择器引擎 Dom Selector Engine,速度号称业界第一。而且它有一个重要的特点就是 Sizzle 是完全独立于 jQuery 的,如果用户不想用 jQuery,还可以只用Sizzle。

Sizzle 强大 DOM 选择器引擎 jQuery 默认选择器引擎

Sizzle 选择器引擎目前成为 jQuery 框架默认的选择器引擎,相比原来的 jQuery 引擎,速度有很大的提升。


:浏览器支持独立的咝咝声和图书馆之间可能会有所不同,请报告问题 Sizzle’s issue tracker,而不是不同的图书馆的跟踪器。

Sizzle 支持:

  • IE 6+
  • FF 3.6+
  • Chrome 14+
  • Safari 4.0+
  • Opera 11.6+
  • Yandex.Browser 14.5+
  • iOS 5.1+
  • Android 2.3, 4.0+

报告在这些浏览器的 Bug,请 add an issue 通过 jsfiddlejsbin 添加一个测试的案例。



用来支持几乎所有的 CSS 3 Selectors,包括选择器(.foo\+bar),Unicode选择器,和结果的文档顺序返回。唯一的例外是那些需要额外的DOM事件侦听器来跟踪的元素的状态。


  • :hover
  • :active
  • :visited, :link


  • :target
  • :root
  • :nth-last-child
  • :nth-of-type, :nth-last-of-type, :first-of-type, :last-of-type, :only-of-type
  • :lang()



  • 充分的选择列表 :not(); 例如 :not(a.b), :not(div > p), :not(div, p)
  • 嵌套伪选择器;例如 :not(:has(div:first-child))


  • [NAME!=VALUE]: 名字属性不指定值匹配的元素。相当于 :not([NAME=VALUE]).
  • :contains(TEXT): 与文本包含单词’TEXT’元素。敏感的。
  • :header: 标题元素(H1,H2,H3,H4,H5,H6)。
  • :parent:至少有一个子节点元素(文本或元素)。
  • :selected: (选项),目前选定的元素


:在这种情况下, input, button, select, 和 textarea 都被认为是输入元素。

  • :input: 输入元素
  • :button: 输入元素可能是 buttons 或者 type 属性是 “button”。
  • :checkbox, :file, :image, :password, :radio, :reset, :submit, :text: 用户指定的输入元素。


在这样的背景下,”positional” 是指一个元素的集合中选择的位置后,基于文档的顺序。例如,div:first 将返回一个数组包含第一 div 在网页上,而 div:first em 将目标第一 div 在页面上选择所有 em 内的元素。


  • :first/:last: 第一/最后一个匹配的元素
  • :even/:odd: 偶数/奇数元素
  • :eq/:nth: 第n个元素;例如: :eq(5) 查找第6个元素
  • :lt/:gt: 在高于/低于指定位置的元素


The Sizzle API consists of 3 parts:

Public API

Sizzle( String selector[, DOMNode context[, Array results]] )

The main function for finding elements. Uses querySelectorAll if available.

returns (Array): All elements matching the selector


selector: A CSS selector

context: An element, document, or document fragment to use as the context for finding elements. Defaults to document.
Note: Prior to version 2.1, document fragments were not valid here.

results: An array or an array-like object, to which Sizzle will append results. For example, jQuery passes a jQuery collection. An “array-like object” is an object with a nonnegative numeric length property and a push method.

Sizzle.matchesSelector( DOMElement element, String selector )

Uses native matchesSelector if available

returns(Boolean): Whether the given element matches the selector


element: A DOMElement against which Sizzle will test the selector

selector: A CSS selector

Sizzle.matches( String selector, Array<DOMElement> elements )

returns(Array): Elements in the array that match the given selector


selector: A CSS selector

elements: An array of DOMElements to filter against the specified selector

Extension API

Sizzle.selectors.match.NAME = RegExp

This contains the regular expressions used to parse a selector into different parts, to be used for finding and filtering. The name of each of the regular expressions should correspond to the names specified in the Sizzle.selectors.find and Sizzle.selectors.filter objects.


In order to add a new find function:

  • A regular expression must be added to the match object.
  • A function to find must be defined.
  • "|" + NAME must be appended to the Sizzle.selectors.order regex.

Sizzle.selectors.find.NAME = function( match, context, isXML ) {}

A method for finding some elements on a page. The specified function will be called no more than once per selector.

  • match is the array of results returned from matching the specified regex against the selector.
  • context is the DOMElement or DOMDocument from which selection will occur.
  • isXML is a boolean value indicating whether the function is currently operating within an XML document.


In order to add a new filtering statement:

  • A regular expression must be added to the match object.
  • A function must be added to the filter object.
  • A function may optionally be added to the preFilter object.

Sizzle.selectors.preFilter.NAME = function( match ) {}

An optional pre-filter function which allows filtering of the matched array against the corresponding regular expression, which will return a new matched array. This matched array will eventually be passed and flattened as arguments against the corresponding filter function. This is intended to clean up some of the repetitive processing that occurs in a filter function.

Sizzle.selectors.filter.NAME: function( element, match[1][, match[2], match[3], ...] ) {}

Note: match[0] will be deleted prior to being passed to a filter, and must not be used.

The arguments for a filter method are the element and the captures from the regex corresponding to this filter (indicated above by what is in the match, starting at index 1). The return result must be boolean: true if the element matches the selector, false if not.


Sizzle.selectors.attrHandle.LOWERCASE_NAME = function( elem, casePreservedName, isXML ) {}

Handle an attribute which requires specialized processing (such as href, which has cross-browser issues). The return result must be the actual string value of that attribute.

Pseudo-selectors (pseudos)

Sizzle.selectors.pseudos.NAME = function( elem ) {}

The most common extension to a selector engine: adding a new pseudo. The return result from this function must be boolean: true if the element matches the selector, false if not.

For example, this defines a simple :fixed pseudo:

var $test = jQuery( document );
Sizzle.selectors.pseudos.fixed = function( elem ) {
    $test[ 0 ] = elem;
    return $test.css( "position" ) === "fixed";


createPseudo is only required if the custom pseudo-selector accepts an argument.

Note: In jQuery 1.8 and earlier, the API for creating custom pseudos with arguments was broken. In jQuery 1.8.1+, the API is backwards-compatible. Regardless, the use of createPseudo is greatly encouraged.

Now that the parser compiles a single function containing other functions, custom pseudo-selectors with arguments are much cleaner.

For example, within Sizzle, the implementation of the :not( <sub-selector> ) pseudo is very similar to:

Sizzle.selectors.pseudos.not =
    Sizzle.selectors.createPseudo(function( subSelector ) {
        var matcher = Sizzle.compile( subSelector );
        return function( elem ) {
            return !matcher( elem );
Backwards-compatible plugins for pseudos with arguments

In order to write a custom selector with arguments that can take advantage of the new API, yet still support all versions of Sizzle, check for the createPseudo method.

The following example uses jQuery syntax. Live example

// An implementation of a case-insensitive contains pseudo
// made for all versions of jQuery
(function( $ ) {

function icontains( elem, text ) {
    return (
        elem.textContent ||
        elem.innerText ||
        $( elem ).text() ||
    ).toLowerCase().indexOf( (text || "").toLowerCase() ) > -1;

$.expr[':'].icontains = $.expr.createPseudo ?
    $.expr.createPseudo(function( text ) {
        return function( elem ) {
            return icontains( elem, text );
    }) :
    function( elem, i, match ) {
        return icontains( elem, match[3] );

})( jQuery );

Sizzle.selectors.setFilters.LOWERCASE_NAME = function( elements, argument, not ) {}

These filters are run after a previous part of a selector has already returned results. setFilters are found from matching Sizzle.selectors.match.POS. When applicable, argument is expected to be an integer. The not argument is a boolean indicating whether the result should be inverted (as in div:not(:first)).

For example, the code for the :first setFilter is similar to:

var first = function( elements, argument, not ) {
    // No argument for first
    return not ? elements.slice( 1 ) : [ elements[0] ];
Sizzle.selectors.setFilters.first = first;

It is easy to extend Sizzle — even Sizzle’s POS selectors. For example, to rename :first as :uno:

Sizzle.selectors.match.POS = new RegExp( oldPOS.source.replace("first", "uno"), "gi" ); = Sizzle.selectors.setFilters.first;
delete Sizzle.selectors.setFilters.first;
Sizzle("div:uno"); // ==> [ <div> ]

Internal API

Note: Functionality should be accessed via the Public and Extension APIs. While the Internal API is intended specifically for internal use, it has been exposed for edge cases.


Sizzle internally caches compiled selector functions and tokenization objects. The length of these caches defaults to 50, but can be set to any positive integer by assigning to this property.

Sizzle.compile( selector )

This method compiles a selector function and caches it for later use. For example, calling Sizzle.compile(".myWidget:myPseudo") during initialization of a plugin will speed up the first selection of matching elements.

returns(Function): The compiled function to be used when filtering the set of possibly matching elements


selector: A CSS selector


如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。



需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。





2891 文章
84935 人气



文章 0 评论


文章 0 评论


文章 0 评论


文章 0 评论


文章 0 评论