2 * Sizzle CSS Selector Engine v2.2.1
5 * Copyright jQuery Foundation and other contributors
6 * Released under the MIT license
7 * http://jquery.org/license
25 // Local document vars
35 // Instance-specific data
36 expando = "sizzle" + 1 * new Date(),
37 preferredDoc = window.document,
40 classCache = createCache(),
41 tokenCache = createCache(),
42 compilerCache = createCache(),
43 sortOrder = function( a, b ) {
50 // General-purpose constants
51 MAX_NEGATIVE = 1 << 31,
54 hasOwn = ({}).hasOwnProperty,
57 push_native = arr.push,
60 // Use a stripped-down indexOf as it's faster than native
61 // http://jsperf.com/thor-indexof-vs-for/5
62 indexOf = function( list, elem ) {
65 for ( ; i < len; i++ ) {
66 if ( list[i] === elem ) {
73 booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
75 // Regular expressions
77 // http://www.w3.org/TR/css3-selectors/#whitespace
78 whitespace = "[\\x20\\t\\r\\n\\f]",
80 // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
81 identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
83 // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
84 attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
85 // Operator (capture 2)
86 "*([*^$|!~]?=)" + whitespace +
87 // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
88 "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
91 pseudos = ":(" + identifier + ")(?:\\((" +
92 // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
93 // 1. quoted (capture 3; capture 4 or capture 5)
94 "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
95 // 2. simple (capture 6)
96 "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
97 // 3. anything else (capture 2)
101 // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
102 rwhitespace = new RegExp( whitespace + "+", "g" ),
103 rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
105 rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
106 rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
108 rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
110 rpseudo = new RegExp( pseudos ),
111 ridentifier = new RegExp( "^" + identifier + "$" ),
114 "ID": new RegExp( "^#(" + identifier + ")" ),
115 "CLASS": new RegExp( "^\\.(" + identifier + ")" ),
116 "TAG": new RegExp( "^(" + identifier + "|[*])" ),
117 "ATTR": new RegExp( "^" + attributes ),
118 "PSEUDO": new RegExp( "^" + pseudos ),
119 "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
120 "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
121 "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
122 "bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
123 // For use in libraries implementing .is()
124 // We use this for POS matching in `select`
125 "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
126 whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
129 rinputs = /^(?:input|select|textarea|button)$/i,
132 rnative = /^[^{]+\{\s*\[native \w/,
134 // Easily-parseable/retrievable ID or TAG or CLASS selectors
135 rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
140 // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
141 runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
142 funescape = function( _, escaped, escapedWhitespace ) {
143 var high = "0x" + escaped - 0x10000;
144 // NaN means non-codepoint
145 // Support: Firefox<24
146 // Workaround erroneous numeric interpretation of +"0x"
147 return high !== high || escapedWhitespace ?
151 String.fromCharCode( high + 0x10000 ) :
152 // Supplemental Plane codepoint (surrogate pair)
153 String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
158 // Removing the function wrapper causes a "Permission Denied"
160 unloadHandler = function() {
164 // Optimize for push.apply( _, NodeList )
167 (arr = slice.call( preferredDoc.childNodes )),
168 preferredDoc.childNodes
170 // Support: Android<4.0
171 // Detect silently failing push.apply
172 arr[ preferredDoc.childNodes.length ].nodeType;
174 push = { apply: arr.length ?
176 // Leverage slice if possible
177 function( target, els ) {
178 push_native.apply( target, slice.call(els) );
182 // Otherwise append directly
183 function( target, els ) {
184 var j = target.length,
186 // Can't trust NodeList.length
187 while ( (target[j++] = els[i++]) ) {}
188 target.length = j - 1;
193 function Sizzle( selector, context, results, seed ) {
194 var m, i, elem, nid, nidselect, match, groups, newSelector,
195 newContext = context && context.ownerDocument,
197 // nodeType defaults to 9, since context defaults to document
198 nodeType = context ? context.nodeType : 9;
200 results = results || [];
202 // Return early from calls with invalid selector or context
203 if ( typeof selector !== "string" || !selector ||
204 nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
209 // Try to shortcut find operations (as opposed to filters) in HTML documents
212 if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
213 setDocument( context );
215 context = context || document;
217 if ( documentIsHTML ) {
219 // If the selector is sufficiently simple, try using a "get*By*" DOM method
220 // (excepting DocumentFragment context, where the methods don't exist)
221 if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
224 if ( (m = match[1]) ) {
227 if ( nodeType === 9 ) {
228 if ( (elem = context.getElementById( m )) ) {
230 // Support: IE, Opera, Webkit
231 // TODO: identify versions
232 // getElementById can match elements by name instead of ID
233 if ( elem.id === m ) {
234 results.push( elem );
244 // Support: IE, Opera, Webkit
245 // TODO: identify versions
246 // getElementById can match elements by name instead of ID
247 if ( newContext && (elem = newContext.getElementById( m )) &&
248 contains( context, elem ) &&
251 results.push( elem );
257 } else if ( match[2] ) {
258 push.apply( results, context.getElementsByTagName( selector ) );
262 } else if ( (m = match[3]) && support.getElementsByClassName &&
263 context.getElementsByClassName ) {
265 push.apply( results, context.getElementsByClassName( m ) );
270 // Take advantage of querySelectorAll
272 !compilerCache[ selector + " " ] &&
273 (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
275 if ( nodeType !== 1 ) {
276 newContext = context;
277 newSelector = selector;
279 // qSA looks outside Element context, which is not what we want
280 // Thanks to Andrew Dupont for this workaround technique
282 // Exclude object elements
283 } else if ( context.nodeName.toLowerCase() !== "object" ) {
285 // Capture the context ID, setting it first if necessary
286 if ( (nid = context.getAttribute( "id" )) ) {
287 nid = nid.replace( rescape, "\\$&" );
289 context.setAttribute( "id", (nid = expando) );
292 // Prefix every selector in the list
293 groups = tokenize( selector );
295 nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']";
297 groups[i] = nidselect + " " + toSelector( groups[i] );
299 newSelector = groups.join( "," );
301 // Expand context for sibling selectors
302 newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
309 newContext.querySelectorAll( newSelector )
312 } catch ( qsaError ) {
314 if ( nid === expando ) {
315 context.removeAttribute( "id" );
324 return select( selector.replace( rtrim, "$1" ), context, results, seed );
328 * Create key-value caches of limited size
329 * @returns {function(string, object)} Returns the Object data after storing it on itself with
330 * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
331 * deleting the oldest entry
333 function createCache() {
336 function cache( key, value ) {
337 // Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
338 if ( keys.push( key + " " ) > Expr.cacheLength ) {
339 // Only keep the most recent entries
340 delete cache[ keys.shift() ];
342 return (cache[ key + " " ] = value);
348 * Mark a function for special use by Sizzle
349 * @param {Function} fn The function to mark
351 function markFunction( fn ) {
352 fn[ expando ] = true;
357 * Support testing using an element
358 * @param {Function} fn Passed the created div and expects a boolean result
360 function assert( fn ) {
361 var div = document.createElement("div");
368 // Remove from its parent by default
369 if ( div.parentNode ) {
370 div.parentNode.removeChild( div );
372 // release memory in IE
378 * Adds the same handler for all of the specified attrs
379 * @param {String} attrs Pipe-separated list of attributes
380 * @param {Function} handler The method that will be applied
382 function addHandle( attrs, handler ) {
383 var arr = attrs.split("|"),
387 Expr.attrHandle[ arr[i] ] = handler;
392 * Checks document order of two siblings
395 * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
397 function siblingCheck( a, b ) {
399 diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
400 ( ~b.sourceIndex || MAX_NEGATIVE ) -
401 ( ~a.sourceIndex || MAX_NEGATIVE );
403 // Use IE sourceIndex if available on both nodes
408 // Check if b follows a
410 while ( (cur = cur.nextSibling) ) {
421 * Returns a function to use in pseudos for input types
422 * @param {String} type
424 function createInputPseudo( type ) {
425 return function( elem ) {
426 var name = elem.nodeName.toLowerCase();
427 return name === "input" && elem.type === type;
432 * Returns a function to use in pseudos for buttons
433 * @param {String} type
435 function createButtonPseudo( type ) {
436 return function( elem ) {
437 var name = elem.nodeName.toLowerCase();
438 return (name === "input" || name === "button") && elem.type === type;
443 * Returns a function to use in pseudos for positionals
444 * @param {Function} fn
446 function createPositionalPseudo( fn ) {
447 return markFunction(function( argument ) {
448 argument = +argument;
449 return markFunction(function( seed, matches ) {
451 matchIndexes = fn( [], seed.length, argument ),
452 i = matchIndexes.length;
454 // Match elements found at the specified indexes
456 if ( seed[ (j = matchIndexes[i]) ] ) {
457 seed[j] = !(matches[j] = seed[j]);
465 * Checks a node for validity as a Sizzle context
466 * @param {Element|Object=} context
467 * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
469 function testContext( context ) {
470 return context && typeof context.getElementsByTagName !== "undefined" && context;
473 // Expose support vars for convenience
474 support = Sizzle.support = {};
478 * @param {Element|Object} elem An element or a document
479 * @returns {Boolean} True iff elem is a non-HTML XML node
481 isXML = Sizzle.isXML = function( elem ) {
482 // documentElement is verified for cases where it doesn't yet exist
483 // (such as loading iframes in IE - #4833)
484 var documentElement = elem && (elem.ownerDocument || elem).documentElement;
485 return documentElement ? documentElement.nodeName !== "HTML" : false;
489 * Sets document-related variables once based on the current document
490 * @param {Element|Object} [doc] An element or document object to use to set the document
491 * @returns {Object} Returns the current document
493 setDocument = Sizzle.setDocument = function( node ) {
494 var hasCompare, parent,
495 doc = node ? node.ownerDocument || node : preferredDoc;
497 // Return early if doc is invalid or already selected
498 if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
502 // Update global variables
504 docElem = document.documentElement;
505 documentIsHTML = !isXML( document );
507 // Support: IE 9-11, Edge
508 // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
509 if ( (parent = document.defaultView) && parent.top !== parent ) {
511 if ( parent.addEventListener ) {
512 parent.addEventListener( "unload", unloadHandler, false );
514 // Support: IE 9 - 10 only
515 } else if ( parent.attachEvent ) {
516 parent.attachEvent( "onunload", unloadHandler );
521 ---------------------------------------------------------------------- */
524 // Verify that getAttribute really returns attributes and not properties
525 // (excepting IE8 booleans)
526 support.attributes = assert(function( div ) {
528 return !div.getAttribute("className");
532 ---------------------------------------------------------------------- */
534 // Check if getElementsByTagName("*") returns only elements
535 support.getElementsByTagName = assert(function( div ) {
536 div.appendChild( document.createComment("") );
537 return !div.getElementsByTagName("*").length;
541 support.getElementsByClassName = rnative.test( document.getElementsByClassName );
544 // Check if getElementById returns elements by name
545 // The broken getElementById methods don't pick up programatically-set names,
546 // so use a roundabout getElementsByName test
547 support.getById = assert(function( div ) {
548 docElem.appendChild( div ).id = expando;
549 return !document.getElementsByName || !document.getElementsByName( expando ).length;
552 // ID find and filter
553 if ( support.getById ) {
554 Expr.find["ID"] = function( id, context ) {
555 if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
556 var m = context.getElementById( id );
557 return m ? [ m ] : [];
560 Expr.filter["ID"] = function( id ) {
561 var attrId = id.replace( runescape, funescape );
562 return function( elem ) {
563 return elem.getAttribute("id") === attrId;
568 // getElementById is not reliable as a find shortcut
569 delete Expr.find["ID"];
571 Expr.filter["ID"] = function( id ) {
572 var attrId = id.replace( runescape, funescape );
573 return function( elem ) {
574 var node = typeof elem.getAttributeNode !== "undefined" &&
575 elem.getAttributeNode("id");
576 return node && node.value === attrId;
582 Expr.find["TAG"] = support.getElementsByTagName ?
583 function( tag, context ) {
584 if ( typeof context.getElementsByTagName !== "undefined" ) {
585 return context.getElementsByTagName( tag );
587 // DocumentFragment nodes don't have gEBTN
588 } else if ( support.qsa ) {
589 return context.querySelectorAll( tag );
593 function( tag, context ) {
597 // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
598 results = context.getElementsByTagName( tag );
600 // Filter out possible comments
602 while ( (elem = results[i++]) ) {
603 if ( elem.nodeType === 1 ) {
614 Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
615 if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
616 return context.getElementsByClassName( className );
620 /* QSA/matchesSelector
621 ---------------------------------------------------------------------- */
623 // QSA and matchesSelector support
625 // matchesSelector(:active) reports false when true (IE9/Opera 11.5)
628 // qSa(:focus) reports false when true (Chrome 21)
629 // We allow this because of a bug in IE8/9 that throws an error
630 // whenever `document.activeElement` is accessed on an iframe
631 // So, we allow :focus to pass through QSA all the time to avoid the IE error
632 // See http://bugs.jquery.com/ticket/13378
635 if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
637 // Regex strategy adopted from Diego Perini
638 assert(function( div ) {
639 // Select is set to empty string on purpose
640 // This is to test IE's treatment of not explicitly
641 // setting a boolean content attribute,
642 // since its presence should be enough
643 // http://bugs.jquery.com/ticket/12359
644 docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" +
645 "<select id='" + expando + "-\r\\' msallowcapture=''>" +
646 "<option selected=''></option></select>";
648 // Support: IE8, Opera 11-12.16
649 // Nothing should be selected when empty strings follow ^= or $= or *=
650 // The test attribute must be unknown in Opera but "safe" for WinRT
651 // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
652 if ( div.querySelectorAll("[msallowcapture^='']").length ) {
653 rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
657 // Boolean attributes and "value" are not treated correctly
658 if ( !div.querySelectorAll("[selected]").length ) {
659 rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
662 // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
663 if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
664 rbuggyQSA.push("~=");
667 // Webkit/Opera - :checked should return selected option elements
668 // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
669 // IE8 throws error here and will not see later tests
670 if ( !div.querySelectorAll(":checked").length ) {
671 rbuggyQSA.push(":checked");
674 // Support: Safari 8+, iOS 8+
675 // https://bugs.webkit.org/show_bug.cgi?id=136851
676 // In-page `selector#id sibing-combinator selector` fails
677 if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
678 rbuggyQSA.push(".#.+[+~]");
682 assert(function( div ) {
683 // Support: Windows 8 Native Apps
684 // The type and name attributes are restricted during .innerHTML assignment
685 var input = document.createElement("input");
686 input.setAttribute( "type", "hidden" );
687 div.appendChild( input ).setAttribute( "name", "D" );
690 // Enforce case-sensitivity of name attribute
691 if ( div.querySelectorAll("[name=d]").length ) {
692 rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
695 // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
696 // IE8 throws error here and will not see later tests
697 if ( !div.querySelectorAll(":enabled").length ) {
698 rbuggyQSA.push( ":enabled", ":disabled" );
701 // Opera 10-11 does not throw on post-comma invalid pseudos
702 div.querySelectorAll("*,:x");
703 rbuggyQSA.push(",.*:");
707 if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
708 docElem.webkitMatchesSelector ||
709 docElem.mozMatchesSelector ||
710 docElem.oMatchesSelector ||
711 docElem.msMatchesSelector) )) ) {
713 assert(function( div ) {
714 // Check to see if it's possible to do matchesSelector
715 // on a disconnected node (IE 9)
716 support.disconnectedMatch = matches.call( div, "div" );
718 // This should fail with an exception
719 // Gecko does not error, returns false instead
720 matches.call( div, "[s!='']:x" );
721 rbuggyMatches.push( "!=", pseudos );
725 rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
726 rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
729 ---------------------------------------------------------------------- */
730 hasCompare = rnative.test( docElem.compareDocumentPosition );
732 // Element contains another
733 // Purposefully self-exclusive
734 // As in, an element does not contain itself
735 contains = hasCompare || rnative.test( docElem.contains ) ?
737 var adown = a.nodeType === 9 ? a.documentElement : a,
738 bup = b && b.parentNode;
739 return a === bup || !!( bup && bup.nodeType === 1 && (
741 adown.contains( bup ) :
742 a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
747 while ( (b = b.parentNode) ) {
757 ---------------------------------------------------------------------- */
759 // Document order sorting
760 sortOrder = hasCompare ?
763 // Flag for duplicate removal
769 // Sort on method existence if only one input has compareDocumentPosition
770 var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
775 // Calculate position if both inputs belong to the same document
776 compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
777 a.compareDocumentPosition( b ) :
779 // Otherwise we know they are disconnected
782 // Disconnected nodes
784 (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
786 // Choose the first element that is related to our preferred document
787 if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
790 if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
794 // Maintain original order
796 ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
800 return compare & 4 ? -1 : 1;
803 // Exit early if the nodes are identical
816 // Parentless nodes are either documents or disconnected
817 if ( !aup || !bup ) {
818 return a === document ? -1 :
823 ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
826 // If the nodes are siblings, we can do a quick check
827 } else if ( aup === bup ) {
828 return siblingCheck( a, b );
831 // Otherwise we need full lists of their ancestors for comparison
833 while ( (cur = cur.parentNode) ) {
837 while ( (cur = cur.parentNode) ) {
841 // Walk down the tree looking for a discrepancy
842 while ( ap[i] === bp[i] ) {
847 // Do a sibling check if the nodes have a common ancestor
848 siblingCheck( ap[i], bp[i] ) :
850 // Otherwise nodes in our document sort first
851 ap[i] === preferredDoc ? -1 :
852 bp[i] === preferredDoc ? 1 :
859 Sizzle.matches = function( expr, elements ) {
860 return Sizzle( expr, null, null, elements );
863 Sizzle.matchesSelector = function( elem, expr ) {
864 // Set document vars if needed
865 if ( ( elem.ownerDocument || elem ) !== document ) {
869 // Make sure that attribute selectors are quoted
870 expr = expr.replace( rattributeQuotes, "='$1']" );
872 if ( support.matchesSelector && documentIsHTML &&
873 !compilerCache[ expr + " " ] &&
874 ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
875 ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
878 var ret = matches.call( elem, expr );
880 // IE 9's matchesSelector returns false on disconnected nodes
881 if ( ret || support.disconnectedMatch ||
882 // As well, disconnected nodes are said to be in a document
884 elem.document && elem.document.nodeType !== 11 ) {
890 return Sizzle( expr, document, null, [ elem ] ).length > 0;
893 Sizzle.contains = function( context, elem ) {
894 // Set document vars if needed
895 if ( ( context.ownerDocument || context ) !== document ) {
896 setDocument( context );
898 return contains( context, elem );
901 Sizzle.attr = function( elem, name ) {
902 // Set document vars if needed
903 if ( ( elem.ownerDocument || elem ) !== document ) {
907 var fn = Expr.attrHandle[ name.toLowerCase() ],
908 // Don't get fooled by Object.prototype properties (jQuery #13807)
909 val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
910 fn( elem, name, !documentIsHTML ) :
913 return val !== undefined ?
915 support.attributes || !documentIsHTML ?
916 elem.getAttribute( name ) :
917 (val = elem.getAttributeNode(name)) && val.specified ?
922 Sizzle.error = function( msg ) {
923 throw new Error( "Syntax error, unrecognized expression: " + msg );
927 * Document sorting and removing duplicates
928 * @param {ArrayLike} results
930 Sizzle.uniqueSort = function( results ) {
936 // Unless we *know* we can detect duplicates, assume their presence
937 hasDuplicate = !support.detectDuplicates;
938 sortInput = !support.sortStable && results.slice( 0 );
939 results.sort( sortOrder );
941 if ( hasDuplicate ) {
942 while ( (elem = results[i++]) ) {
943 if ( elem === results[ i ] ) {
944 j = duplicates.push( i );
948 results.splice( duplicates[ j ], 1 );
952 // Clear input after sorting to release objects
953 // See https://github.com/jquery/sizzle/pull/225
960 * Utility function for retrieving the text value of an array of DOM nodes
961 * @param {Array|Element} elem
963 getText = Sizzle.getText = function( elem ) {
967 nodeType = elem.nodeType;
970 // If no nodeType, this is expected to be an array
971 while ( (node = elem[i++]) ) {
972 // Do not traverse comment nodes
973 ret += getText( node );
975 } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
976 // Use textContent for elements
977 // innerText usage removed for consistency of new lines (jQuery #11153)
978 if ( typeof elem.textContent === "string" ) {
979 return elem.textContent;
981 // Traverse its children
982 for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
983 ret += getText( elem );
986 } else if ( nodeType === 3 || nodeType === 4 ) {
987 return elem.nodeValue;
989 // Do not include comment or processing instruction nodes
994 Expr = Sizzle.selectors = {
996 // Can be adjusted by the user
999 createPseudo: markFunction,
1008 ">": { dir: "parentNode", first: true },
1009 " ": { dir: "parentNode" },
1010 "+": { dir: "previousSibling", first: true },
1011 "~": { dir: "previousSibling" }
1015 "ATTR": function( match ) {
1016 match[1] = match[1].replace( runescape, funescape );
1018 // Move the given value to match[3] whether quoted or unquoted
1019 match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
1021 if ( match[2] === "~=" ) {
1022 match[3] = " " + match[3] + " ";
1025 return match.slice( 0, 4 );
1028 "CHILD": function( match ) {
1029 /* matches from matchExpr["CHILD"]
1030 1 type (only|nth|...)
1031 2 what (child|of-type)
1032 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
1033 4 xn-component of xn+y argument ([+-]?\d*n|)
1034 5 sign of xn-component
1036 7 sign of y-component
1039 match[1] = match[1].toLowerCase();
1041 if ( match[1].slice( 0, 3 ) === "nth" ) {
1042 // nth-* requires argument
1044 Sizzle.error( match[0] );
1047 // numeric x and y parameters for Expr.filter.CHILD
1048 // remember that false/true cast respectively to 0/1
1049 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
1050 match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
1052 // other types prohibit arguments
1053 } else if ( match[3] ) {
1054 Sizzle.error( match[0] );
1060 "PSEUDO": function( match ) {
1062 unquoted = !match[6] && match[2];
1064 if ( matchExpr["CHILD"].test( match[0] ) ) {
1068 // Accept quoted arguments as-is
1070 match[2] = match[4] || match[5] || "";
1072 // Strip excess characters from unquoted arguments
1073 } else if ( unquoted && rpseudo.test( unquoted ) &&
1074 // Get excess from tokenize (recursively)
1075 (excess = tokenize( unquoted, true )) &&
1076 // advance to the next closing parenthesis
1077 (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
1079 // excess is a negative index
1080 match[0] = match[0].slice( 0, excess );
1081 match[2] = unquoted.slice( 0, excess );
1084 // Return only captures needed by the pseudo filter method (type and argument)
1085 return match.slice( 0, 3 );
1091 "TAG": function( nodeNameSelector ) {
1092 var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
1093 return nodeNameSelector === "*" ?
1094 function() { return true; } :
1096 return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
1100 "CLASS": function( className ) {
1101 var pattern = classCache[ className + " " ];
1104 (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
1105 classCache( className, function( elem ) {
1106 return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
1110 "ATTR": function( name, operator, check ) {
1111 return function( elem ) {
1112 var result = Sizzle.attr( elem, name );
1114 if ( result == null ) {
1115 return operator === "!=";
1123 return operator === "=" ? result === check :
1124 operator === "!=" ? result !== check :
1125 operator === "^=" ? check && result.indexOf( check ) === 0 :
1126 operator === "*=" ? check && result.indexOf( check ) > -1 :
1127 operator === "$=" ? check && result.slice( -check.length ) === check :
1128 operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
1129 operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
1134 "CHILD": function( type, what, argument, first, last ) {
1135 var simple = type.slice( 0, 3 ) !== "nth",
1136 forward = type.slice( -4 ) !== "last",
1137 ofType = what === "of-type";
1139 return first === 1 && last === 0 ?
1141 // Shortcut for :nth-*(n)
1143 return !!elem.parentNode;
1146 function( elem, context, xml ) {
1147 var cache, uniqueCache, outerCache, node, nodeIndex, start,
1148 dir = simple !== forward ? "nextSibling" : "previousSibling",
1149 parent = elem.parentNode,
1150 name = ofType && elem.nodeName.toLowerCase(),
1151 useCache = !xml && !ofType,
1156 // :(first|last|only)-(child|of-type)
1160 while ( (node = node[ dir ]) ) {
1162 node.nodeName.toLowerCase() === name :
1163 node.nodeType === 1 ) {
1168 // Reverse direction for :only-* (if we haven't yet done so)
1169 start = dir = type === "only" && !start && "nextSibling";
1174 start = [ forward ? parent.firstChild : parent.lastChild ];
1176 // non-xml :nth-child(...) stores cache data on `parent`
1177 if ( forward && useCache ) {
1179 // Seek `elem` from a previously-cached index
1181 // ...in a gzip-friendly way
1183 outerCache = node[ expando ] || (node[ expando ] = {});
1185 // Support: IE <9 only
1186 // Defend against cloned attroperties (jQuery gh-1709)
1187 uniqueCache = outerCache[ node.uniqueID ] ||
1188 (outerCache[ node.uniqueID ] = {});
1190 cache = uniqueCache[ type ] || [];
1191 nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
1192 diff = nodeIndex && cache[ 2 ];
1193 node = nodeIndex && parent.childNodes[ nodeIndex ];
1195 while ( (node = ++nodeIndex && node && node[ dir ] ||
1197 // Fallback to seeking `elem` from the start
1198 (diff = nodeIndex = 0) || start.pop()) ) {
1200 // When found, cache indexes on `parent` and break
1201 if ( node.nodeType === 1 && ++diff && node === elem ) {
1202 uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
1208 // Use previously-cached element index if available
1210 // ...in a gzip-friendly way
1212 outerCache = node[ expando ] || (node[ expando ] = {});
1214 // Support: IE <9 only
1215 // Defend against cloned attroperties (jQuery gh-1709)
1216 uniqueCache = outerCache[ node.uniqueID ] ||
1217 (outerCache[ node.uniqueID ] = {});
1219 cache = uniqueCache[ type ] || [];
1220 nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
1224 // xml :nth-child(...)
1225 // or :nth-last-child(...) or :nth(-last)?-of-type(...)
1226 if ( diff === false ) {
1227 // Use the same loop as above to seek `elem` from the start
1228 while ( (node = ++nodeIndex && node && node[ dir ] ||
1229 (diff = nodeIndex = 0) || start.pop()) ) {
1232 node.nodeName.toLowerCase() === name :
1233 node.nodeType === 1 ) &&
1236 // Cache the index of each encountered element
1238 outerCache = node[ expando ] || (node[ expando ] = {});
1240 // Support: IE <9 only
1241 // Defend against cloned attroperties (jQuery gh-1709)
1242 uniqueCache = outerCache[ node.uniqueID ] ||
1243 (outerCache[ node.uniqueID ] = {});
1245 uniqueCache[ type ] = [ dirruns, diff ];
1248 if ( node === elem ) {
1256 // Incorporate the offset, then check against cycle size
1258 return diff === first || ( diff % first === 0 && diff / first >= 0 );
1263 "PSEUDO": function( pseudo, argument ) {
1264 // pseudo-class names are case-insensitive
1265 // http://www.w3.org/TR/selectors/#pseudo-classes
1266 // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
1267 // Remember that setFilters inherits from pseudos
1269 fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
1270 Sizzle.error( "unsupported pseudo: " + pseudo );
1272 // The user may use createPseudo to indicate that
1273 // arguments are needed to create the filter function
1274 // just as Sizzle does
1275 if ( fn[ expando ] ) {
1276 return fn( argument );
1279 // But maintain support for old signatures
1280 if ( fn.length > 1 ) {
1281 args = [ pseudo, pseudo, "", argument ];
1282 return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
1283 markFunction(function( seed, matches ) {
1285 matched = fn( seed, argument ),
1288 idx = indexOf( seed, matched[i] );
1289 seed[ idx ] = !( matches[ idx ] = matched[i] );
1293 return fn( elem, 0, args );
1302 // Potentially complex pseudos
1303 "not": markFunction(function( selector ) {
1304 // Trim the selector passed to compile
1305 // to avoid treating leading and trailing
1306 // spaces as combinators
1309 matcher = compile( selector.replace( rtrim, "$1" ) );
1311 return matcher[ expando ] ?
1312 markFunction(function( seed, matches, context, xml ) {
1314 unmatched = matcher( seed, null, xml, [] ),
1317 // Match elements unmatched by `matcher`
1319 if ( (elem = unmatched[i]) ) {
1320 seed[i] = !(matches[i] = elem);
1324 function( elem, context, xml ) {
1326 matcher( input, null, xml, results );
1327 // Don't keep the element (issue #299)
1329 return !results.pop();
1333 "has": markFunction(function( selector ) {
1334 return function( elem ) {
1335 return Sizzle( selector, elem ).length > 0;
1339 "contains": markFunction(function( text ) {
1340 text = text.replace( runescape, funescape );
1341 return function( elem ) {
1342 return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
1346 // "Whether an element is represented by a :lang() selector
1347 // is based solely on the element's language value
1348 // being equal to the identifier C,
1349 // or beginning with the identifier C immediately followed by "-".
1350 // The matching of C against the element's language value is performed case-insensitively.
1351 // The identifier C does not have to be a valid language name."
1352 // http://www.w3.org/TR/selectors/#lang-pseudo
1353 "lang": markFunction( function( lang ) {
1354 // lang value must be a valid identifier
1355 if ( !ridentifier.test(lang || "") ) {
1356 Sizzle.error( "unsupported lang: " + lang );
1358 lang = lang.replace( runescape, funescape ).toLowerCase();
1359 return function( elem ) {
1362 if ( (elemLang = documentIsHTML ?
1364 elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
1366 elemLang = elemLang.toLowerCase();
1367 return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
1369 } while ( (elem = elem.parentNode) && elem.nodeType === 1 );
1375 "target": function( elem ) {
1376 var hash = window.location && window.location.hash;
1377 return hash && hash.slice( 1 ) === elem.id;
1380 "root": function( elem ) {
1381 return elem === docElem;
1384 "focus": function( elem ) {
1385 return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
1388 // Boolean properties
1389 "enabled": function( elem ) {
1390 return elem.disabled === false;
1393 "disabled": function( elem ) {
1394 return elem.disabled === true;
1397 "checked": function( elem ) {
1398 // In CSS3, :checked should return both checked and selected elements
1399 // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
1400 var nodeName = elem.nodeName.toLowerCase();
1401 return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
1404 "selected": function( elem ) {
1405 // Accessing this property makes selected-by-default
1406 // options in Safari work properly
1407 if ( elem.parentNode ) {
1408 elem.parentNode.selectedIndex;
1411 return elem.selected === true;
1415 "empty": function( elem ) {
1416 // http://www.w3.org/TR/selectors/#empty-pseudo
1417 // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
1418 // but not by others (comment: 8; processing instruction: 7; etc.)
1419 // nodeType < 6 works because attributes (2) do not appear as children
1420 for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
1421 if ( elem.nodeType < 6 ) {
1428 "parent": function( elem ) {
1429 return !Expr.pseudos["empty"]( elem );
1432 // Element/input types
1433 "header": function( elem ) {
1434 return rheader.test( elem.nodeName );
1437 "input": function( elem ) {
1438 return rinputs.test( elem.nodeName );
1441 "button": function( elem ) {
1442 var name = elem.nodeName.toLowerCase();
1443 return name === "input" && elem.type === "button" || name === "button";
1446 "text": function( elem ) {
1448 return elem.nodeName.toLowerCase() === "input" &&
1449 elem.type === "text" &&
1452 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
1453 ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
1456 // Position-in-collection
1457 "first": createPositionalPseudo(function() {
1461 "last": createPositionalPseudo(function( matchIndexes, length ) {
1462 return [ length - 1 ];
1465 "eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
1466 return [ argument < 0 ? argument + length : argument ];
1469 "even": createPositionalPseudo(function( matchIndexes, length ) {
1471 for ( ; i < length; i += 2 ) {
1472 matchIndexes.push( i );
1474 return matchIndexes;
1477 "odd": createPositionalPseudo(function( matchIndexes, length ) {
1479 for ( ; i < length; i += 2 ) {
1480 matchIndexes.push( i );
1482 return matchIndexes;
1485 "lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
1486 var i = argument < 0 ? argument + length : argument;
1487 for ( ; --i >= 0; ) {
1488 matchIndexes.push( i );
1490 return matchIndexes;
1493 "gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
1494 var i = argument < 0 ? argument + length : argument;
1495 for ( ; ++i < length; ) {
1496 matchIndexes.push( i );
1498 return matchIndexes;
1503 Expr.pseudos["nth"] = Expr.pseudos["eq"];
1505 // Add button/input type pseudos
1506 for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
1507 Expr.pseudos[ i ] = createInputPseudo( i );
1509 for ( i in { submit: true, reset: true } ) {
1510 Expr.pseudos[ i ] = createButtonPseudo( i );
1513 // Easy API for creating new setFilters
1514 function setFilters() {}
1515 setFilters.prototype = Expr.filters = Expr.pseudos;
1516 Expr.setFilters = new setFilters();
1518 tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
1519 var matched, match, tokens, type,
1520 soFar, groups, preFilters,
1521 cached = tokenCache[ selector + " " ];
1524 return parseOnly ? 0 : cached.slice( 0 );
1529 preFilters = Expr.preFilter;
1533 // Comma and first run
1534 if ( !matched || (match = rcomma.exec( soFar )) ) {
1536 // Don't consume trailing commas as valid
1537 soFar = soFar.slice( match[0].length ) || soFar;
1539 groups.push( (tokens = []) );
1545 if ( (match = rcombinators.exec( soFar )) ) {
1546 matched = match.shift();
1549 // Cast descendant combinators to space
1550 type: match[0].replace( rtrim, " " )
1552 soFar = soFar.slice( matched.length );
1556 for ( type in Expr.filter ) {
1557 if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
1558 (match = preFilters[ type ]( match ))) ) {
1559 matched = match.shift();
1565 soFar = soFar.slice( matched.length );
1574 // Return the length of the invalid excess
1575 // if we're just parsing
1576 // Otherwise, throw an error or return tokens
1580 Sizzle.error( selector ) :
1582 tokenCache( selector, groups ).slice( 0 );
1585 function toSelector( tokens ) {
1587 len = tokens.length,
1589 for ( ; i < len; i++ ) {
1590 selector += tokens[i].value;
1595 function addCombinator( matcher, combinator, base ) {
1596 var dir = combinator.dir,
1597 checkNonElements = base && dir === "parentNode",
1600 return combinator.first ?
1601 // Check against closest ancestor/preceding element
1602 function( elem, context, xml ) {
1603 while ( (elem = elem[ dir ]) ) {
1604 if ( elem.nodeType === 1 || checkNonElements ) {
1605 return matcher( elem, context, xml );
1610 // Check against all ancestor/preceding elements
1611 function( elem, context, xml ) {
1612 var oldCache, uniqueCache, outerCache,
1613 newCache = [ dirruns, doneName ];
1615 // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
1617 while ( (elem = elem[ dir ]) ) {
1618 if ( elem.nodeType === 1 || checkNonElements ) {
1619 if ( matcher( elem, context, xml ) ) {
1625 while ( (elem = elem[ dir ]) ) {
1626 if ( elem.nodeType === 1 || checkNonElements ) {
1627 outerCache = elem[ expando ] || (elem[ expando ] = {});
1629 // Support: IE <9 only
1630 // Defend against cloned attroperties (jQuery gh-1709)
1631 uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
1633 if ( (oldCache = uniqueCache[ dir ]) &&
1634 oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
1636 // Assign to newCache so results back-propagate to previous elements
1637 return (newCache[ 2 ] = oldCache[ 2 ]);
1639 // Reuse newcache so results back-propagate to previous elements
1640 uniqueCache[ dir ] = newCache;
1642 // A match means we're done; a fail means we have to keep checking
1643 if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
1653 function elementMatcher( matchers ) {
1654 return matchers.length > 1 ?
1655 function( elem, context, xml ) {
1656 var i = matchers.length;
1658 if ( !matchers[i]( elem, context, xml ) ) {
1667 function multipleContexts( selector, contexts, results ) {
1669 len = contexts.length;
1670 for ( ; i < len; i++ ) {
1671 Sizzle( selector, contexts[i], results );
1676 function condense( unmatched, map, filter, context, xml ) {
1680 len = unmatched.length,
1681 mapped = map != null;
1683 for ( ; i < len; i++ ) {
1684 if ( (elem = unmatched[i]) ) {
1685 if ( !filter || filter( elem, context, xml ) ) {
1686 newUnmatched.push( elem );
1694 return newUnmatched;
1697 function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
1698 if ( postFilter && !postFilter[ expando ] ) {
1699 postFilter = setMatcher( postFilter );
1701 if ( postFinder && !postFinder[ expando ] ) {
1702 postFinder = setMatcher( postFinder, postSelector );
1704 return markFunction(function( seed, results, context, xml ) {
1708 preexisting = results.length,
1710 // Get initial elements from seed or context
1711 elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
1713 // Prefilter to get matcher input, preserving a map for seed-results synchronization
1714 matcherIn = preFilter && ( seed || !selector ) ?
1715 condense( elems, preMap, preFilter, context, xml ) :
1718 matcherOut = matcher ?
1719 // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
1720 postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
1722 // ...intermediate processing is necessary
1725 // ...otherwise use results directly
1729 // Find primary matches
1731 matcher( matcherIn, matcherOut, context, xml );
1736 temp = condense( matcherOut, postMap );
1737 postFilter( temp, [], context, xml );
1739 // Un-match failing elements by moving them back to matcherIn
1742 if ( (elem = temp[i]) ) {
1743 matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
1749 if ( postFinder || preFilter ) {
1751 // Get the final matcherOut by condensing this intermediate into postFinder contexts
1753 i = matcherOut.length;
1755 if ( (elem = matcherOut[i]) ) {
1756 // Restore matcherIn since elem is not yet a final match
1757 temp.push( (matcherIn[i] = elem) );
1760 postFinder( null, (matcherOut = []), temp, xml );
1763 // Move matched elements from seed to results to keep them synchronized
1764 i = matcherOut.length;
1766 if ( (elem = matcherOut[i]) &&
1767 (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
1769 seed[temp] = !(results[temp] = elem);
1774 // Add elements to results, through postFinder if defined
1776 matcherOut = condense(
1777 matcherOut === results ?
1778 matcherOut.splice( preexisting, matcherOut.length ) :
1782 postFinder( null, results, matcherOut, xml );
1784 push.apply( results, matcherOut );
1790 function matcherFromTokens( tokens ) {
1791 var checkContext, matcher, j,
1792 len = tokens.length,
1793 leadingRelative = Expr.relative[ tokens[0].type ],
1794 implicitRelative = leadingRelative || Expr.relative[" "],
1795 i = leadingRelative ? 1 : 0,
1797 // The foundational matcher ensures that elements are reachable from top-level context(s)
1798 matchContext = addCombinator( function( elem ) {
1799 return elem === checkContext;
1800 }, implicitRelative, true ),
1801 matchAnyContext = addCombinator( function( elem ) {
1802 return indexOf( checkContext, elem ) > -1;
1803 }, implicitRelative, true ),
1804 matchers = [ function( elem, context, xml ) {
1805 var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
1806 (checkContext = context).nodeType ?
1807 matchContext( elem, context, xml ) :
1808 matchAnyContext( elem, context, xml ) );
1809 // Avoid hanging onto element (issue #299)
1810 checkContext = null;
1814 for ( ; i < len; i++ ) {
1815 if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
1816 matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
1818 matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
1820 // Return special upon seeing a positional matcher
1821 if ( matcher[ expando ] ) {
1822 // Find the next relative operator (if any) for proper handling
1824 for ( ; j < len; j++ ) {
1825 if ( Expr.relative[ tokens[j].type ] ) {
1830 i > 1 && elementMatcher( matchers ),
1831 i > 1 && toSelector(
1832 // If the preceding token was a descendant combinator, insert an implicit any-element `*`
1833 tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
1834 ).replace( rtrim, "$1" ),
1836 i < j && matcherFromTokens( tokens.slice( i, j ) ),
1837 j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
1838 j < len && toSelector( tokens )
1841 matchers.push( matcher );
1845 return elementMatcher( matchers );
1848 function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
1849 var bySet = setMatchers.length > 0,
1850 byElement = elementMatchers.length > 0,
1851 superMatcher = function( seed, context, xml, results, outermost ) {
1852 var elem, j, matcher,
1855 unmatched = seed && [],
1857 contextBackup = outermostContext,
1858 // We must always have either seed elements or outermost context
1859 elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
1860 // Use integer dirruns iff this is the outermost matcher
1861 dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
1865 outermostContext = context === document || context || outermost;
1868 // Add elements passing elementMatchers directly to results
1869 // Support: IE<9, Safari
1870 // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
1871 for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
1872 if ( byElement && elem ) {
1874 if ( !context && elem.ownerDocument !== document ) {
1875 setDocument( elem );
1876 xml = !documentIsHTML;
1878 while ( (matcher = elementMatchers[j++]) ) {
1879 if ( matcher( elem, context || document, xml) ) {
1880 results.push( elem );
1885 dirruns = dirrunsUnique;
1889 // Track unmatched elements for set filters
1891 // They will have gone through all possible matchers
1892 if ( (elem = !matcher && elem) ) {
1896 // Lengthen the array for every element, matched or not
1898 unmatched.push( elem );
1903 // `i` is now the count of elements visited above, and adding it to `matchedCount`
1904 // makes the latter nonnegative.
1907 // Apply set filters to unmatched elements
1908 // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
1909 // equals `i`), unless we didn't visit _any_ elements in the above loop because we have
1910 // no element matchers and no seed.
1911 // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
1912 // case, which will result in a "00" `matchedCount` that differs from `i` but is also
1913 // numerically zero.
1914 if ( bySet && i !== matchedCount ) {
1916 while ( (matcher = setMatchers[j++]) ) {
1917 matcher( unmatched, setMatched, context, xml );
1921 // Reintegrate element matches to eliminate the need for sorting
1922 if ( matchedCount > 0 ) {
1924 if ( !(unmatched[i] || setMatched[i]) ) {
1925 setMatched[i] = pop.call( results );
1930 // Discard index placeholder values to get only actual matches
1931 setMatched = condense( setMatched );
1934 // Add matches to results
1935 push.apply( results, setMatched );
1937 // Seedless set matches succeeding multiple successful matchers stipulate sorting
1938 if ( outermost && !seed && setMatched.length > 0 &&
1939 ( matchedCount + setMatchers.length ) > 1 ) {
1941 Sizzle.uniqueSort( results );
1945 // Override manipulation of globals by nested matchers
1947 dirruns = dirrunsUnique;
1948 outermostContext = contextBackup;
1955 markFunction( superMatcher ) :
1959 compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
1962 elementMatchers = [],
1963 cached = compilerCache[ selector + " " ];
1966 // Generate a function of recursive functions that can be used to check each element
1968 match = tokenize( selector );
1972 cached = matcherFromTokens( match[i] );
1973 if ( cached[ expando ] ) {
1974 setMatchers.push( cached );
1976 elementMatchers.push( cached );
1980 // Cache the compiled function
1981 cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
1983 // Save selector and tokenization
1984 cached.selector = selector;
1990 * A low-level selection function that works with Sizzle's compiled
1991 * selector functions
1992 * @param {String|Function} selector A selector or a pre-compiled
1993 * selector function built with Sizzle.compile
1994 * @param {Element} context
1995 * @param {Array} [results]
1996 * @param {Array} [seed] A set of elements to match against
1998 select = Sizzle.select = function( selector, context, results, seed ) {
1999 var i, tokens, token, type, find,
2000 compiled = typeof selector === "function" && selector,
2001 match = !seed && tokenize( (selector = compiled.selector || selector) );
2003 results = results || [];
2005 // Try to minimize operations if there is only one selector in the list and no seed
2006 // (the latter of which guarantees us context)
2007 if ( match.length === 1 ) {
2009 // Reduce context if the leading compound selector is an ID
2010 tokens = match[0] = match[0].slice( 0 );
2011 if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
2012 support.getById && context.nodeType === 9 && documentIsHTML &&
2013 Expr.relative[ tokens[1].type ] ) {
2015 context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
2019 // Precompiled matchers will still verify ancestry, so step up a level
2020 } else if ( compiled ) {
2021 context = context.parentNode;
2024 selector = selector.slice( tokens.shift().value.length );
2027 // Fetch a seed set for right-to-left matching
2028 i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
2032 // Abort if we hit a combinator
2033 if ( Expr.relative[ (type = token.type) ] ) {
2036 if ( (find = Expr.find[ type ]) ) {
2037 // Search, expanding context for leading sibling combinators
2039 token.matches[0].replace( runescape, funescape ),
2040 rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
2043 // If seed is empty or no tokens remain, we can return early
2044 tokens.splice( i, 1 );
2045 selector = seed.length && toSelector( tokens );
2047 push.apply( results, seed );
2057 // Compile and execute a filtering function if one is not provided
2058 // Provide `match` to avoid retokenization if we modified the selector above
2059 ( compiled || compile( selector, match ) )(
2064 !context || rsibling.test( selector ) && testContext( context.parentNode ) || context
2069 // One-time assignments
2072 support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
2074 // Support: Chrome 14-35+
2075 // Always assume duplicates if they aren't passed to the comparison function
2076 support.detectDuplicates = !!hasDuplicate;
2078 // Initialize against the default document
2081 // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
2082 // Detached nodes confoundingly follow *each other*
2083 support.sortDetached = assert(function( div1 ) {
2084 // Should return 1, but returns 4 (following)
2085 return div1.compareDocumentPosition( document.createElement("div") ) & 1;
2089 // Prevent attribute/property "interpolation"
2090 // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
2091 if ( !assert(function( div ) {
2092 div.innerHTML = "<a href='#'></a>";
2093 return div.firstChild.getAttribute("href") === "#" ;
2095 addHandle( "type|href|height|width", function( elem, name, isXML ) {
2097 return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
2103 // Use defaultValue in place of getAttribute("value")
2104 if ( !support.attributes || !assert(function( div ) {
2105 div.innerHTML = "<input/>";
2106 div.firstChild.setAttribute( "value", "" );
2107 return div.firstChild.getAttribute( "value" ) === "";
2109 addHandle( "value", function( elem, name, isXML ) {
2110 if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
2111 return elem.defaultValue;
2117 // Use getAttributeNode to fetch booleans when getAttribute lies
2118 if ( !assert(function( div ) {
2119 return div.getAttribute("disabled") == null;
2121 addHandle( booleans, function( elem, name, isXML ) {
2124 return elem[ name ] === true ? name.toLowerCase() :
2125 (val = elem.getAttributeNode( name )) && val.specified ?
2133 if ( typeof define === "function" && define.amd ) {
2134 define(function() { return Sizzle; });
2135 // Sizzle requires that there be a global window in Common-JS like environments
2136 } else if ( typeof module !== "undefined" && module.exports ) {
2137 module.exports = Sizzle;
2139 window.Sizzle = Sizzle;