1 import { jQuery } from "./core.js";
2 import { nodeName } from "./core/nodeName.js";
3 import { document as preferredDoc } from "./var/document.js";
4 import { indexOf } from "./var/indexOf.js";
5 import { pop } from "./var/pop.js";
6 import { push } from "./var/push.js";
7 import { whitespace } from "./var/whitespace.js";
8 import { rbuggyQSA } from "./selector/rbuggyQSA.js";
9 import { rtrimCSS } from "./var/rtrimCSS.js";
10 import { isIE } from "./var/isIE.js";
11 import { identifier } from "./selector/var/identifier.js";
12 import { rleadingCombinator } from "./selector/var/rleadingCombinator.js";
13 import { rdescend } from "./selector/var/rdescend.js";
14 import { rsibling } from "./selector/var/rsibling.js";
15 import { matches } from "./selector/var/matches.js";
16 import { createCache } from "./selector/createCache.js";
17 import { testContext } from "./selector/testContext.js";
18 import { filterMatchExpr } from "./selector/filterMatchExpr.js";
19 import { preFilter } from "./selector/preFilter.js";
20 import { selectorError } from "./selector/selectorError.js";
21 import { unescapeSelector } from "./selector/unescapeSelector.js";
22 import { tokenize } from "./selector/tokenize.js";
23 import { toSelector } from "./selector/toSelector.js";
25 // The following utils are attached directly to the jQuery object.
26 import "./attributes/attr.js"; // jQuery.attr
27 import "./selector/escapeSelector.js";
28 import "./selector/uniqueSort.js";
33 // Local document vars
38 // Instance-specific data
41 classCache = createCache(),
42 compilerCache = createCache(),
43 nonnativeSelectorCache = createCache(),
45 // Regular expressions
47 // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
48 rwhitespace = new RegExp( whitespace + "+", "g" ),
50 ridentifier = new RegExp( "^" + identifier + "$" ),
52 matchExpr = jQuery.extend( {
54 // For use in libraries implementing .is()
55 // We use this for POS matching in `select`
56 needsContext: new RegExp( "^" + whitespace +
57 "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +
58 "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
61 rinputs = /^(?:input|select|textarea|button)$/i,
64 // Easily-parseable/retrievable ID or TAG or CLASS selectors
65 rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
67 // Used for iframes; see `setDocument`.
68 // Support: IE 9 - 11+
69 // Removing the function wrapper causes a "Permission Denied"
71 unloadHandler = function() {
75 inDisabledFieldset = addCombinator(
77 return elem.disabled === true && nodeName( elem, "fieldset" );
79 { dir: "parentNode", next: "legend" }
82 function find( selector, context, results, seed ) {
83 var m, i, elem, nid, match, groups, newSelector,
84 newContext = context && context.ownerDocument,
86 // nodeType defaults to 9, since context defaults to document
87 nodeType = context ? context.nodeType : 9;
89 results = results || [];
91 // Return early from calls with invalid selector or context
92 if ( typeof selector !== "string" || !selector ||
93 nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
98 // Try to shortcut find operations (as opposed to filters) in HTML documents
100 setDocument( context );
101 context = context || document;
103 if ( documentIsHTML ) {
105 // If the selector is sufficiently simple, try using a "get*By*" DOM method
106 // (excepting DocumentFragment context, where the methods don't exist)
107 if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) {
110 if ( ( m = match[ 1 ] ) ) {
113 if ( nodeType === 9 ) {
114 if ( ( elem = context.getElementById( m ) ) ) {
115 push.call( results, elem );
121 if ( newContext && ( elem = newContext.getElementById( m ) ) &&
122 jQuery.contains( context, elem ) ) {
124 push.call( results, elem );
130 } else if ( match[ 2 ] ) {
131 push.apply( results, context.getElementsByTagName( selector ) );
135 } else if ( ( m = match[ 3 ] ) && context.getElementsByClassName ) {
136 push.apply( results, context.getElementsByClassName( m ) );
141 // Take advantage of querySelectorAll
142 if ( !nonnativeSelectorCache[ selector + " " ] &&
143 ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) ) {
145 newSelector = selector;
146 newContext = context;
148 // qSA considers elements outside a scoping root when evaluating child or
149 // descendant combinators, which is not what we want.
150 // In such cases, we work around the behavior by prefixing every selector in the
151 // list with an ID selector referencing the scope context.
152 // The technique has to be used as well when a leading combinator is used
153 // as such selectors are not recognized by querySelectorAll.
154 // Thanks to Andrew Dupont for this technique.
155 if ( nodeType === 1 &&
156 ( rdescend.test( selector ) || rleadingCombinator.test( selector ) ) ) {
158 // Expand context for sibling selectors
159 newContext = rsibling.test( selector ) &&
160 testContext( context.parentNode ) ||
163 // Outside of IE, if we're not changing the context we can
164 // use :scope instead of an ID.
166 // IE sometimes throws a "Permission denied" error when strict-comparing
167 // two documents; shallow comparisons work.
168 // eslint-disable-next-line eqeqeq
169 if ( newContext != context || isIE ) {
171 // Capture the context ID, setting it first if necessary
172 if ( ( nid = context.getAttribute( "id" ) ) ) {
173 nid = jQuery.escapeSelector( nid );
175 context.setAttribute( "id", ( nid = jQuery.expando ) );
179 // Prefix every selector in the list
180 groups = tokenize( selector );
183 groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " +
184 toSelector( groups[ i ] );
186 newSelector = groups.join( "," );
191 newContext.querySelectorAll( newSelector )
194 } catch ( qsaError ) {
195 nonnativeSelectorCache( selector, true );
197 if ( nid === jQuery.expando ) {
198 context.removeAttribute( "id" );
206 return select( selector.replace( rtrimCSS, "$1" ), context, results, seed );
210 * Mark a function for special use by jQuery selector module
211 * @param {Function} fn The function to mark
213 function markFunction( fn ) {
214 fn[ jQuery.expando ] = true;
219 * Returns a function to use in pseudos for input types
220 * @param {String} type
222 function createInputPseudo( type ) {
223 return function( elem ) {
224 return nodeName( elem, "input" ) && elem.type === type;
229 * Returns a function to use in pseudos for buttons
230 * @param {String} type
232 function createButtonPseudo( type ) {
233 return function( elem ) {
234 return ( nodeName( elem, "input" ) || nodeName( elem, "button" ) ) &&
240 * Returns a function to use in pseudos for :enabled/:disabled
241 * @param {Boolean} disabled true for :disabled; false for :enabled
243 function createDisabledPseudo( disabled ) {
245 // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
246 return function( elem ) {
248 // Only certain elements can match :enabled or :disabled
249 // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
250 // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
251 if ( "form" in elem ) {
253 // Check for inherited disabledness on relevant non-disabled elements:
254 // * listed form-associated elements in a disabled fieldset
255 // https://html.spec.whatwg.org/multipage/forms.html#category-listed
256 // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
257 // * option elements in a disabled optgroup
258 // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
259 // All such elements have a "form" property.
260 if ( elem.parentNode && elem.disabled === false ) {
262 // Option elements defer to a parent optgroup if present
263 if ( "label" in elem ) {
264 if ( "label" in elem.parentNode ) {
265 return elem.parentNode.disabled === disabled;
267 return elem.disabled === disabled;
271 // Support: IE 6 - 11+
272 // Use the isDisabled shortcut property to check for disabled fieldset ancestors
273 return elem.isDisabled === disabled ||
275 // Where there is no isDisabled, check manually
276 elem.isDisabled !== !disabled &&
277 inDisabledFieldset( elem ) === disabled;
280 return elem.disabled === disabled;
282 // Try to winnow out elements that can't be disabled before trusting the disabled property.
283 // Some victims get caught in our net (label, legend, menu, track), but it shouldn't
284 // even exist on them, let alone have a boolean value.
285 } else if ( "label" in elem ) {
286 return elem.disabled === disabled;
289 // Remaining elements are neither :enabled nor :disabled
295 * Returns a function to use in pseudos for positionals
296 * @param {Function} fn
298 function createPositionalPseudo( fn ) {
299 return markFunction( function( argument ) {
300 argument = +argument;
301 return markFunction( function( seed, matches ) {
303 matchIndexes = fn( [], seed.length, argument ),
304 i = matchIndexes.length;
306 // Match elements found at the specified indexes
308 if ( seed[ ( j = matchIndexes[ i ] ) ] ) {
309 seed[ j ] = !( matches[ j ] = seed[ j ] );
317 * Sets document-related variables once based on the current document
318 * @param {Element|Object} [node] An element or document object to use to set the document
320 function setDocument( node ) {
322 doc = node ? node.ownerDocument || node : preferredDoc;
324 // Return early if doc is invalid or already selected
326 // IE sometimes throws a "Permission denied" error when strict-comparing
327 // two documents; shallow comparisons work.
328 // eslint-disable-next-line eqeqeq
329 if ( doc == document || doc.nodeType !== 9 ) {
333 // Update global variables
335 documentElement = document.documentElement;
336 documentIsHTML = !jQuery.isXMLDoc( document );
338 // Support: IE 9 - 11+
339 // Accessing iframe documents after unload throws "permission denied" errors (see trac-13936)
341 // IE sometimes throws a "Permission denied" error when strict-comparing
342 // two documents; shallow comparisons work.
343 // eslint-disable-next-line eqeqeq
344 if ( isIE && preferredDoc != document &&
345 ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) {
346 subWindow.addEventListener( "unload", unloadHandler );
350 find.matches = function( expr, elements ) {
351 return find( expr, null, null, elements );
354 find.matchesSelector = function( elem, expr ) {
357 if ( documentIsHTML &&
358 !nonnativeSelectorCache[ expr + " " ] &&
359 ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
362 return matches.call( elem, expr );
364 nonnativeSelectorCache( expr, true );
368 return find( expr, document, null, [ elem ] ).length > 0;
373 // Can be adjusted by the user
376 createPseudo: markFunction,
381 ID: function( id, context ) {
382 if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
383 var elem = context.getElementById( id );
384 return elem ? [ elem ] : [];
388 TAG: function( tag, context ) {
389 if ( typeof context.getElementsByTagName !== "undefined" ) {
390 return context.getElementsByTagName( tag );
392 // DocumentFragment nodes don't have gEBTN
394 return context.querySelectorAll( tag );
398 CLASS: function( className, context ) {
399 if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
400 return context.getElementsByClassName( className );
406 ">": { dir: "parentNode", first: true },
407 " ": { dir: "parentNode" },
408 "+": { dir: "previousSibling", first: true },
409 "~": { dir: "previousSibling" }
412 preFilter: preFilter,
416 var attrId = unescapeSelector( id );
417 return function( elem ) {
418 return elem.getAttribute( "id" ) === attrId;
422 TAG: function( nodeNameSelector ) {
423 var expectedNodeName = unescapeSelector( nodeNameSelector ).toLowerCase();
424 return nodeNameSelector === "*" ?
431 return nodeName( elem, expectedNodeName );
435 CLASS: function( className ) {
436 var pattern = classCache[ className + " " ];
439 ( pattern = new RegExp( "(^|" + whitespace + ")" + className +
440 "(" + whitespace + "|$)" ) ) &&
441 classCache( className, function( elem ) {
443 typeof elem.className === "string" && elem.className ||
444 typeof elem.getAttribute !== "undefined" &&
445 elem.getAttribute( "class" ) ||
451 ATTR: function( name, operator, check ) {
452 return function( elem ) {
453 var result = jQuery.attr( elem, name );
455 if ( result == null ) {
456 return operator === "!=";
464 if ( operator === "=" ) {
465 return result === check;
467 if ( operator === "!=" ) {
468 return result !== check;
470 if ( operator === "^=" ) {
471 return check && result.indexOf( check ) === 0;
473 if ( operator === "*=" ) {
474 return check && result.indexOf( check ) > -1;
476 if ( operator === "$=" ) {
477 return check && result.slice( -check.length ) === check;
479 if ( operator === "~=" ) {
480 return ( " " + result.replace( rwhitespace, " " ) + " " )
481 .indexOf( check ) > -1;
483 if ( operator === "|=" ) {
484 return result === check || result.slice( 0, check.length + 1 ) === check + "-";
491 CHILD: function( type, what, _argument, first, last ) {
492 var simple = type.slice( 0, 3 ) !== "nth",
493 forward = type.slice( -4 ) !== "last",
494 ofType = what === "of-type";
496 return first === 1 && last === 0 ?
498 // Shortcut for :nth-*(n)
500 return !!elem.parentNode;
503 function( elem, _context, xml ) {
504 var cache, outerCache, node, nodeIndex, start,
505 dir = simple !== forward ? "nextSibling" : "previousSibling",
506 parent = elem.parentNode,
507 name = ofType && elem.nodeName.toLowerCase(),
508 useCache = !xml && !ofType,
513 // :(first|last|only)-(child|of-type)
517 while ( ( node = node[ dir ] ) ) {
519 nodeName( node, name ) :
520 node.nodeType === 1 ) {
526 // Reverse direction for :only-* (if we haven't yet done so)
527 start = dir = type === "only" && !start && "nextSibling";
532 start = [ forward ? parent.firstChild : parent.lastChild ];
534 // non-xml :nth-child(...) stores cache data on `parent`
535 if ( forward && useCache ) {
537 // Seek `elem` from a previously-cached index
538 outerCache = parent[ jQuery.expando ] ||
539 ( parent[ jQuery.expando ] = {} );
540 cache = outerCache[ type ] || [];
541 nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
542 diff = nodeIndex && cache[ 2 ];
543 node = nodeIndex && parent.childNodes[ nodeIndex ];
545 while ( ( node = ++nodeIndex && node && node[ dir ] ||
547 // Fallback to seeking `elem` from the start
548 ( diff = nodeIndex = 0 ) || start.pop() ) ) {
550 // When found, cache indexes on `parent` and break
551 if ( node.nodeType === 1 && ++diff && node === elem ) {
552 outerCache[ type ] = [ dirruns, nodeIndex, diff ];
559 // Use previously-cached element index if available
561 outerCache = elem[ jQuery.expando ] ||
562 ( elem[ jQuery.expando ] = {} );
563 cache = outerCache[ type ] || [];
564 nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
568 // xml :nth-child(...)
569 // or :nth-last-child(...) or :nth(-last)?-of-type(...)
570 if ( diff === false ) {
572 // Use the same loop as above to seek `elem` from the start
573 while ( ( node = ++nodeIndex && node && node[ dir ] ||
574 ( diff = nodeIndex = 0 ) || start.pop() ) ) {
577 nodeName( node, name ) :
578 node.nodeType === 1 ) &&
581 // Cache the index of each encountered element
583 outerCache = node[ jQuery.expando ] ||
584 ( node[ jQuery.expando ] = {} );
585 outerCache[ type ] = [ dirruns, diff ];
588 if ( node === elem ) {
596 // Incorporate the offset, then check against cycle size
598 return diff === first || ( diff % first === 0 && diff / first >= 0 );
603 PSEUDO: function( pseudo, argument ) {
605 // pseudo-class names are case-insensitive
606 // https://www.w3.org/TR/selectors/#pseudo-classes
607 // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
608 // Remember that setFilters inherits from pseudos
609 var fn = jQuery.expr.pseudos[ pseudo ] ||
610 jQuery.expr.setFilters[ pseudo.toLowerCase() ] ||
611 selectorError( "unsupported pseudo: " + pseudo );
613 // The user may use createPseudo to indicate that
614 // arguments are needed to create the filter function
615 // just as jQuery does
616 if ( fn[ jQuery.expando ] ) {
617 return fn( argument );
626 // Potentially complex pseudos
627 not: markFunction( function( selector ) {
629 // Trim the selector passed to compile
630 // to avoid treating leading and trailing
631 // spaces as combinators
634 matcher = compile( selector.replace( rtrimCSS, "$1" ) );
636 return matcher[ jQuery.expando ] ?
637 markFunction( function( seed, matches, _context, xml ) {
639 unmatched = matcher( seed, null, xml, [] ),
642 // Match elements unmatched by `matcher`
644 if ( ( elem = unmatched[ i ] ) ) {
645 seed[ i ] = !( matches[ i ] = elem );
649 function( elem, _context, xml ) {
651 matcher( input, null, xml, results );
653 // Don't keep the element
654 // (see https://github.com/jquery/sizzle/issues/299)
656 return !results.pop();
660 has: markFunction( function( selector ) {
661 return function( elem ) {
662 return find( selector, elem ).length > 0;
666 contains: markFunction( function( text ) {
667 text = unescapeSelector( text );
668 return function( elem ) {
669 return ( elem.textContent || jQuery.text( elem ) ).indexOf( text ) > -1;
673 // "Whether an element is represented by a :lang() selector
674 // is based solely on the element's language value
675 // being equal to the identifier C,
676 // or beginning with the identifier C immediately followed by "-".
677 // The matching of C against the element's language value is performed case-insensitively.
678 // The identifier C does not have to be a valid language name."
679 // https://www.w3.org/TR/selectors/#lang-pseudo
680 lang: markFunction( function( lang ) {
682 // lang value must be a valid identifier
683 if ( !ridentifier.test( lang || "" ) ) {
684 selectorError( "unsupported lang: " + lang );
686 lang = unescapeSelector( lang ).toLowerCase();
687 return function( elem ) {
690 if ( ( elemLang = documentIsHTML ?
692 elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) {
694 elemLang = elemLang.toLowerCase();
695 return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
697 } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 );
703 target: function( elem ) {
704 var hash = window.location && window.location.hash;
705 return hash && hash.slice( 1 ) === elem.id;
708 root: function( elem ) {
709 return elem === documentElement;
712 focus: function( elem ) {
713 return elem === document.activeElement &&
714 document.hasFocus() &&
715 !!( elem.type || elem.href || ~elem.tabIndex );
718 // Boolean properties
719 enabled: createDisabledPseudo( false ),
720 disabled: createDisabledPseudo( true ),
722 checked: function( elem ) {
724 // In CSS3, :checked should return both checked and selected elements
725 // https://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
726 return ( nodeName( elem, "input" ) && !!elem.checked ) ||
727 ( nodeName( elem, "option" ) && !!elem.selected );
730 selected: function( elem ) {
733 // Accessing the selectedIndex property
734 // forces the browser to treat the default option as
735 // selected when in an optgroup.
736 if ( isIE && elem.parentNode ) {
737 // eslint-disable-next-line no-unused-expressions
738 elem.parentNode.selectedIndex;
741 return elem.selected === true;
745 empty: function( elem ) {
747 // https://www.w3.org/TR/selectors/#empty-pseudo
748 // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
749 // but not by others (comment: 8; processing instruction: 7; etc.)
750 // nodeType < 6 works because attributes (2) do not appear as children
751 for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
752 if ( elem.nodeType < 6 ) {
759 parent: function( elem ) {
760 return !jQuery.expr.pseudos.empty( elem );
763 // Element/input types
764 header: function( elem ) {
765 return rheader.test( elem.nodeName );
768 input: function( elem ) {
769 return rinputs.test( elem.nodeName );
772 button: function( elem ) {
773 return nodeName( elem, "input" ) && elem.type === "button" ||
774 nodeName( elem, "button" );
777 text: function( elem ) {
778 return nodeName( elem, "input" ) && elem.type === "text";
781 // Position-in-collection
782 first: createPositionalPseudo( function() {
786 last: createPositionalPseudo( function( _matchIndexes, length ) {
787 return [ length - 1 ];
790 eq: createPositionalPseudo( function( _matchIndexes, length, argument ) {
791 return [ argument < 0 ? argument + length : argument ];
794 even: createPositionalPseudo( function( matchIndexes, length ) {
796 for ( ; i < length; i += 2 ) {
797 matchIndexes.push( i );
802 odd: createPositionalPseudo( function( matchIndexes, length ) {
804 for ( ; i < length; i += 2 ) {
805 matchIndexes.push( i );
810 lt: createPositionalPseudo( function( matchIndexes, length, argument ) {
813 if ( argument < 0 ) {
814 i = argument + length;
815 } else if ( argument > length ) {
821 for ( ; --i >= 0; ) {
822 matchIndexes.push( i );
827 gt: createPositionalPseudo( function( matchIndexes, length, argument ) {
828 var i = argument < 0 ? argument + length : argument;
829 for ( ; ++i < length; ) {
830 matchIndexes.push( i );
837 jQuery.expr.pseudos.nth = jQuery.expr.pseudos.eq;
839 // Add button/input type pseudos
840 for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
841 jQuery.expr.pseudos[ i ] = createInputPseudo( i );
843 for ( i in { submit: true, reset: true } ) {
844 jQuery.expr.pseudos[ i ] = createButtonPseudo( i );
847 // Easy API for creating new setFilters
848 function setFilters() {}
849 setFilters.prototype = jQuery.expr.filters = jQuery.expr.pseudos;
850 jQuery.expr.setFilters = new setFilters();
852 function addCombinator( matcher, combinator, base ) {
853 var dir = combinator.dir,
854 skip = combinator.next,
856 checkNonElements = base && key === "parentNode",
859 return combinator.first ?
861 // Check against closest ancestor/preceding element
862 function( elem, context, xml ) {
863 while ( ( elem = elem[ dir ] ) ) {
864 if ( elem.nodeType === 1 || checkNonElements ) {
865 return matcher( elem, context, xml );
871 // Check against all ancestor/preceding elements
872 function( elem, context, xml ) {
873 var oldCache, outerCache,
874 newCache = [ dirruns, doneName ];
876 // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
878 while ( ( elem = elem[ dir ] ) ) {
879 if ( elem.nodeType === 1 || checkNonElements ) {
880 if ( matcher( elem, context, xml ) ) {
886 while ( ( elem = elem[ dir ] ) ) {
887 if ( elem.nodeType === 1 || checkNonElements ) {
888 outerCache = elem[ jQuery.expando ] || ( elem[ jQuery.expando ] = {} );
890 if ( skip && nodeName( elem, skip ) ) {
891 elem = elem[ dir ] || elem;
892 } else if ( ( oldCache = outerCache[ key ] ) &&
893 oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
895 // Assign to newCache so results back-propagate to previous elements
896 return ( newCache[ 2 ] = oldCache[ 2 ] );
899 // Reuse newcache so results back-propagate to previous elements
900 outerCache[ key ] = newCache;
902 // A match means we're done; a fail means we have to keep checking
903 if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) {
914 function elementMatcher( matchers ) {
915 return matchers.length > 1 ?
916 function( elem, context, xml ) {
917 var i = matchers.length;
919 if ( !matchers[ i ]( elem, context, xml ) ) {
928 function multipleContexts( selector, contexts, results ) {
930 len = contexts.length;
931 for ( ; i < len; i++ ) {
932 find( selector, contexts[ i ], results );
937 function condense( unmatched, map, filter, context, xml ) {
941 len = unmatched.length,
942 mapped = map != null;
944 for ( ; i < len; i++ ) {
945 if ( ( elem = unmatched[ i ] ) ) {
946 if ( !filter || filter( elem, context, xml ) ) {
947 newUnmatched.push( elem );
958 function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
959 if ( postFilter && !postFilter[ jQuery.expando ] ) {
960 postFilter = setMatcher( postFilter );
962 if ( postFinder && !postFinder[ jQuery.expando ] ) {
963 postFinder = setMatcher( postFinder, postSelector );
965 return markFunction( function( seed, results, context, xml ) {
966 var temp, i, elem, matcherOut,
969 preexisting = results.length,
971 // Get initial elements from seed or context
973 multipleContexts( selector || "*",
974 context.nodeType ? [ context ] : context, [] ),
976 // Prefilter to get matcher input, preserving a map for seed-results synchronization
977 matcherIn = preFilter && ( seed || !selector ) ?
978 condense( elems, preMap, preFilter, context, xml ) :
983 // If we have a postFinder, or filtered seed, or non-seed postFilter
984 // or preexisting results,
985 matcherOut = postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
987 // ...intermediate processing is necessary
990 // ...otherwise use results directly
993 // Find primary matches
994 matcher( matcherIn, matcherOut, context, xml );
996 matcherOut = matcherIn;
1001 temp = condense( matcherOut, postMap );
1002 postFilter( temp, [], context, xml );
1004 // Un-match failing elements by moving them back to matcherIn
1007 if ( ( elem = temp[ i ] ) ) {
1008 matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem );
1014 if ( postFinder || preFilter ) {
1017 // Get the final matcherOut by condensing this intermediate into postFinder contexts
1019 i = matcherOut.length;
1021 if ( ( elem = matcherOut[ i ] ) ) {
1023 // Restore matcherIn since elem is not yet a final match
1024 temp.push( ( matcherIn[ i ] = elem ) );
1027 postFinder( null, ( matcherOut = [] ), temp, xml );
1030 // Move matched elements from seed to results to keep them synchronized
1031 i = matcherOut.length;
1033 if ( ( elem = matcherOut[ i ] ) &&
1034 ( temp = postFinder ? indexOf.call( seed, elem ) : preMap[ i ] ) > -1 ) {
1036 seed[ temp ] = !( results[ temp ] = elem );
1041 // Add elements to results, through postFinder if defined
1043 matcherOut = condense(
1044 matcherOut === results ?
1045 matcherOut.splice( preexisting, matcherOut.length ) :
1049 postFinder( null, results, matcherOut, xml );
1051 push.apply( results, matcherOut );
1057 function matcherFromTokens( tokens ) {
1058 var checkContext, matcher, j,
1059 len = tokens.length,
1060 leadingRelative = jQuery.expr.relative[ tokens[ 0 ].type ],
1061 implicitRelative = leadingRelative || jQuery.expr.relative[ " " ],
1062 i = leadingRelative ? 1 : 0,
1064 // The foundational matcher ensures that elements are reachable from top-level context(s)
1065 matchContext = addCombinator( function( elem ) {
1066 return elem === checkContext;
1067 }, implicitRelative, true ),
1068 matchAnyContext = addCombinator( function( elem ) {
1069 return indexOf.call( checkContext, elem ) > -1;
1070 }, implicitRelative, true ),
1071 matchers = [ function( elem, context, xml ) {
1074 // IE sometimes throws a "Permission denied" error when strict-comparing
1075 // two documents; shallow comparisons work.
1076 // eslint-disable-next-line eqeqeq
1077 var ret = ( !leadingRelative && ( xml || context != outermostContext ) ) || (
1078 ( checkContext = context ).nodeType ?
1079 matchContext( elem, context, xml ) :
1080 matchAnyContext( elem, context, xml ) );
1082 // Avoid hanging onto element
1083 // (see https://github.com/jquery/sizzle/issues/299)
1084 checkContext = null;
1088 for ( ; i < len; i++ ) {
1089 if ( ( matcher = jQuery.expr.relative[ tokens[ i ].type ] ) ) {
1090 matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
1092 matcher = jQuery.expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches );
1094 // Return special upon seeing a positional matcher
1095 if ( matcher[ jQuery.expando ] ) {
1097 // Find the next relative operator (if any) for proper handling
1099 for ( ; j < len; j++ ) {
1100 if ( jQuery.expr.relative[ tokens[ j ].type ] ) {
1105 i > 1 && elementMatcher( matchers ),
1106 i > 1 && toSelector(
1108 // If the preceding token was a descendant combinator, insert an implicit any-element `*`
1109 tokens.slice( 0, i - 1 )
1110 .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } )
1111 ).replace( rtrimCSS, "$1" ),
1113 i < j && matcherFromTokens( tokens.slice( i, j ) ),
1114 j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ),
1115 j < len && toSelector( tokens )
1118 matchers.push( matcher );
1122 return elementMatcher( matchers );
1125 function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
1126 var bySet = setMatchers.length > 0,
1127 byElement = elementMatchers.length > 0,
1128 superMatcher = function( seed, context, xml, results, outermost ) {
1129 var elem, j, matcher,
1132 unmatched = seed && [],
1134 contextBackup = outermostContext,
1136 // We must always have either seed elements or outermost context
1137 elems = seed || byElement && jQuery.expr.find.TAG( "*", outermost ),
1139 // Use integer dirruns iff this is the outermost matcher
1140 dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 );
1145 // IE sometimes throws a "Permission denied" error when strict-comparing
1146 // two documents; shallow comparisons work.
1147 // eslint-disable-next-line eqeqeq
1148 outermostContext = context == document || context || outermost;
1151 // Add elements passing elementMatchers directly to results
1152 for ( ; ( elem = elems[ i ] ) != null; i++ ) {
1153 if ( byElement && elem ) {
1157 // IE sometimes throws a "Permission denied" error when strict-comparing
1158 // two documents; shallow comparisons work.
1159 // eslint-disable-next-line eqeqeq
1160 if ( !context && elem.ownerDocument != document ) {
1161 setDocument( elem );
1162 xml = !documentIsHTML;
1164 while ( ( matcher = elementMatchers[ j++ ] ) ) {
1165 if ( matcher( elem, context || document, xml ) ) {
1166 push.call( results, elem );
1171 dirruns = dirrunsUnique;
1175 // Track unmatched elements for set filters
1178 // They will have gone through all possible matchers
1179 if ( ( elem = !matcher && elem ) ) {
1183 // Lengthen the array for every element, matched or not
1185 unmatched.push( elem );
1190 // `i` is now the count of elements visited above, and adding it to `matchedCount`
1191 // makes the latter nonnegative.
1194 // Apply set filters to unmatched elements
1195 // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
1196 // equals `i`), unless we didn't visit _any_ elements in the above loop because we have
1197 // no element matchers and no seed.
1198 // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
1199 // case, which will result in a "00" `matchedCount` that differs from `i` but is also
1200 // numerically zero.
1201 if ( bySet && i !== matchedCount ) {
1203 while ( ( matcher = setMatchers[ j++ ] ) ) {
1204 matcher( unmatched, setMatched, context, xml );
1209 // Reintegrate element matches to eliminate the need for sorting
1210 if ( matchedCount > 0 ) {
1212 if ( !( unmatched[ i ] || setMatched[ i ] ) ) {
1213 setMatched[ i ] = pop.call( results );
1218 // Discard index placeholder values to get only actual matches
1219 setMatched = condense( setMatched );
1222 // Add matches to results
1223 push.apply( results, setMatched );
1225 // Seedless set matches succeeding multiple successful matchers stipulate sorting
1226 if ( outermost && !seed && setMatched.length > 0 &&
1227 ( matchedCount + setMatchers.length ) > 1 ) {
1229 jQuery.uniqueSort( results );
1233 // Override manipulation of globals by nested matchers
1235 dirruns = dirrunsUnique;
1236 outermostContext = contextBackup;
1243 markFunction( superMatcher ) :
1247 function compile( selector, match /* Internal Use Only */ ) {
1250 elementMatchers = [],
1251 cached = compilerCache[ selector + " " ];
1255 // Generate a function of recursive functions that can be used to check each element
1257 match = tokenize( selector );
1261 cached = matcherFromTokens( match[ i ] );
1262 if ( cached[ jQuery.expando ] ) {
1263 setMatchers.push( cached );
1265 elementMatchers.push( cached );
1269 // Cache the compiled function
1270 cached = compilerCache( selector,
1271 matcherFromGroupMatchers( elementMatchers, setMatchers ) );
1273 // Save selector and tokenization
1274 cached.selector = selector;
1280 * A low-level selection function that works with jQuery's compiled
1281 * selector functions
1282 * @param {String|Function} selector A selector or a pre-compiled
1283 * selector function built with jQuery selector compile
1284 * @param {Element} context
1285 * @param {Array} [results]
1286 * @param {Array} [seed] A set of elements to match against
1288 function select( selector, context, results, seed ) {
1289 var i, tokens, token, type, find,
1290 compiled = typeof selector === "function" && selector,
1291 match = !seed && tokenize( ( selector = compiled.selector || selector ) );
1293 results = results || [];
1295 // Try to minimize operations if there is only one selector in the list and no seed
1296 // (the latter of which guarantees us context)
1297 if ( match.length === 1 ) {
1299 // Reduce context if the leading compound selector is an ID
1300 tokens = match[ 0 ] = match[ 0 ].slice( 0 );
1301 if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" &&
1302 context.nodeType === 9 && documentIsHTML &&
1303 jQuery.expr.relative[ tokens[ 1 ].type ] ) {
1305 context = ( jQuery.expr.find.ID(
1306 unescapeSelector( token.matches[ 0 ] ),
1312 // Precompiled matchers will still verify ancestry, so step up a level
1313 } else if ( compiled ) {
1314 context = context.parentNode;
1317 selector = selector.slice( tokens.shift().value.length );
1320 // Fetch a seed set for right-to-left matching
1321 i = matchExpr.needsContext.test( selector ) ? 0 : tokens.length;
1323 token = tokens[ i ];
1325 // Abort if we hit a combinator
1326 if ( jQuery.expr.relative[ ( type = token.type ) ] ) {
1329 if ( ( find = jQuery.expr.find[ type ] ) ) {
1331 // Search, expanding context for leading sibling combinators
1333 unescapeSelector( token.matches[ 0 ] ),
1334 rsibling.test( tokens[ 0 ].type ) &&
1335 testContext( context.parentNode ) || context
1338 // If seed is empty or no tokens remain, we can return early
1339 tokens.splice( i, 1 );
1340 selector = seed.length && toSelector( tokens );
1342 push.apply( results, seed );
1352 // Compile and execute a filtering function if one is not provided
1353 // Provide `match` to avoid retokenization if we modified the selector above
1354 ( compiled || compile( selector, match ) )(
1359 !context || rsibling.test( selector ) && testContext( context.parentNode ) || context
1364 // Initialize against the default document
1369 // These have always been private, but they used to be documented as part of
1370 // Sizzle so let's maintain them for now for backwards compatibility purposes.
1371 find.compile = compile;
1372 find.select = select;
1373 find.setDocument = setDocument;
1374 find.tokenize = tokenize;
1376 export { jQuery, jQuery as $ };