2 * Sizzle CSS Selector Engine v2.3.3
3 * https://sizzlejs.com/
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 ) {
51 hasOwn = ({}).hasOwnProperty,
54 push_native = arr.push,
57 // Use a stripped-down indexOf as it's faster than native
58 // https://jsperf.com/thor-indexof-vs-for/5
59 indexOf = function( list, elem ) {
62 for ( ; i < len; i++ ) {
63 if ( list[i] === elem ) {
70 booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
72 // Regular expressions
74 // http://www.w3.org/TR/css3-selectors/#whitespace
75 whitespace = "[\\x20\\t\\r\\n\\f]",
77 // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
78 identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+",
80 // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
81 attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
82 // Operator (capture 2)
83 "*([*^$|!~]?=)" + whitespace +
84 // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
85 "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
88 pseudos = ":(" + identifier + ")(?:\\((" +
89 // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
90 // 1. quoted (capture 3; capture 4 or capture 5)
91 "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
92 // 2. simple (capture 6)
93 "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
94 // 3. anything else (capture 2)
98 // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
99 rwhitespace = new RegExp( whitespace + "+", "g" ),
100 rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
102 rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
103 rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
105 rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
107 rpseudo = new RegExp( pseudos ),
108 ridentifier = new RegExp( "^" + identifier + "$" ),
111 "ID": new RegExp( "^#(" + identifier + ")" ),
112 "CLASS": new RegExp( "^\\.(" + identifier + ")" ),
113 "TAG": new RegExp( "^(" + identifier + "|[*])" ),
114 "ATTR": new RegExp( "^" + attributes ),
115 "PSEUDO": new RegExp( "^" + pseudos ),
116 "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
117 "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
118 "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
119 "bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
120 // For use in libraries implementing .is()
121 // We use this for POS matching in `select`
122 "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
123 whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
126 rinputs = /^(?:input|select|textarea|button)$/i,
129 rnative = /^[^{]+\{\s*\[native \w/,
131 // Easily-parseable/retrievable ID or TAG or CLASS selectors
132 rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
137 // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
138 runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
139 funescape = function( _, escaped, escapedWhitespace ) {
140 var high = "0x" + escaped - 0x10000;
141 // NaN means non-codepoint
142 // Support: Firefox<24
143 // Workaround erroneous numeric interpretation of +"0x"
144 return high !== high || escapedWhitespace ?
148 String.fromCharCode( high + 0x10000 ) :
149 // Supplemental Plane codepoint (surrogate pair)
150 String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
153 // CSS string/identifier serialization
154 // https://drafts.csswg.org/cssom/#common-serializing-idioms
155 rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,
156 fcssescape = function( ch, asCodePoint ) {
159 // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
164 // Control characters and (dependent upon position) numbers get escaped as code points
165 return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
168 // Other potentially-special ASCII characters get backslash-escaped
174 // Removing the function wrapper causes a "Permission Denied"
176 unloadHandler = function() {
180 disabledAncestor = addCombinator(
182 return elem.disabled === true && ("form" in elem || "label" in elem);
184 { dir: "parentNode", next: "legend" }
187 // Optimize for push.apply( _, NodeList )
190 (arr = slice.call( preferredDoc.childNodes )),
191 preferredDoc.childNodes
193 // Support: Android<4.0
194 // Detect silently failing push.apply
195 arr[ preferredDoc.childNodes.length ].nodeType;
197 push = { apply: arr.length ?
199 // Leverage slice if possible
200 function( target, els ) {
201 push_native.apply( target, slice.call(els) );
205 // Otherwise append directly
206 function( target, els ) {
207 var j = target.length,
209 // Can't trust NodeList.length
210 while ( (target[j++] = els[i++]) ) {}
211 target.length = j - 1;
216 function Sizzle( selector, context, results, seed ) {
217 var m, i, elem, nid, match, groups, newSelector,
218 newContext = context && context.ownerDocument,
220 // nodeType defaults to 9, since context defaults to document
221 nodeType = context ? context.nodeType : 9;
223 results = results || [];
225 // Return early from calls with invalid selector or context
226 if ( typeof selector !== "string" || !selector ||
227 nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
232 // Try to shortcut find operations (as opposed to filters) in HTML documents
235 if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
236 setDocument( context );
238 context = context || document;
240 if ( documentIsHTML ) {
242 // If the selector is sufficiently simple, try using a "get*By*" DOM method
243 // (excepting DocumentFragment context, where the methods don't exist)
244 if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
247 if ( (m = match[1]) ) {
250 if ( nodeType === 9 ) {
251 if ( (elem = context.getElementById( m )) ) {
253 // Support: IE, Opera, Webkit
254 // TODO: identify versions
255 // getElementById can match elements by name instead of ID
256 if ( elem.id === m ) {
257 results.push( elem );
267 // Support: IE, Opera, Webkit
268 // TODO: identify versions
269 // getElementById can match elements by name instead of ID
270 if ( newContext && (elem = newContext.getElementById( m )) &&
271 contains( context, elem ) &&
274 results.push( elem );
280 } else if ( match[2] ) {
281 push.apply( results, context.getElementsByTagName( selector ) );
285 } else if ( (m = match[3]) && support.getElementsByClassName &&
286 context.getElementsByClassName ) {
288 push.apply( results, context.getElementsByClassName( m ) );
293 // Take advantage of querySelectorAll
295 !compilerCache[ selector + " " ] &&
296 (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
298 if ( nodeType !== 1 ) {
299 newContext = context;
300 newSelector = selector;
302 // qSA looks outside Element context, which is not what we want
303 // Thanks to Andrew Dupont for this workaround technique
305 // Exclude object elements
306 } else if ( context.nodeName.toLowerCase() !== "object" ) {
308 // Capture the context ID, setting it first if necessary
309 if ( (nid = context.getAttribute( "id" )) ) {
310 nid = nid.replace( rcssescape, fcssescape );
312 context.setAttribute( "id", (nid = expando) );
315 // Prefix every selector in the list
316 groups = tokenize( selector );
319 groups[i] = "#" + nid + " " + toSelector( groups[i] );
321 newSelector = groups.join( "," );
323 // Expand context for sibling selectors
324 newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
331 newContext.querySelectorAll( newSelector )
334 } catch ( qsaError ) {
336 if ( nid === expando ) {
337 context.removeAttribute( "id" );
346 return select( selector.replace( rtrim, "$1" ), context, results, seed );
350 * Create key-value caches of limited size
351 * @returns {function(string, object)} Returns the Object data after storing it on itself with
352 * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
353 * deleting the oldest entry
355 function createCache() {
358 function cache( key, value ) {
359 // Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
360 if ( keys.push( key + " " ) > Expr.cacheLength ) {
361 // Only keep the most recent entries
362 delete cache[ keys.shift() ];
364 return (cache[ key + " " ] = value);
370 * Mark a function for special use by Sizzle
371 * @param {Function} fn The function to mark
373 function markFunction( fn ) {
374 fn[ expando ] = true;
379 * Support testing using an element
380 * @param {Function} fn Passed the created element and returns a boolean result
382 function assert( fn ) {
383 var el = document.createElement("fieldset");
390 // Remove from its parent by default
391 if ( el.parentNode ) {
392 el.parentNode.removeChild( el );
394 // release memory in IE
400 * Adds the same handler for all of the specified attrs
401 * @param {String} attrs Pipe-separated list of attributes
402 * @param {Function} handler The method that will be applied
404 function addHandle( attrs, handler ) {
405 var arr = attrs.split("|"),
409 Expr.attrHandle[ arr[i] ] = handler;
414 * Checks document order of two siblings
417 * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
419 function siblingCheck( a, b ) {
421 diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
422 a.sourceIndex - b.sourceIndex;
424 // Use IE sourceIndex if available on both nodes
429 // Check if b follows a
431 while ( (cur = cur.nextSibling) ) {
442 * Returns a function to use in pseudos for input types
443 * @param {String} type
445 function createInputPseudo( type ) {
446 return function( elem ) {
447 var name = elem.nodeName.toLowerCase();
448 return name === "input" && elem.type === type;
453 * Returns a function to use in pseudos for buttons
454 * @param {String} type
456 function createButtonPseudo( type ) {
457 return function( elem ) {
458 var name = elem.nodeName.toLowerCase();
459 return (name === "input" || name === "button") && elem.type === type;
464 * Returns a function to use in pseudos for :enabled/:disabled
465 * @param {Boolean} disabled true for :disabled; false for :enabled
467 function createDisabledPseudo( disabled ) {
469 // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
470 return function( elem ) {
472 // Only certain elements can match :enabled or :disabled
473 // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
474 // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
475 if ( "form" in elem ) {
477 // Check for inherited disabledness on relevant non-disabled elements:
478 // * listed form-associated elements in a disabled fieldset
479 // https://html.spec.whatwg.org/multipage/forms.html#category-listed
480 // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
481 // * option elements in a disabled optgroup
482 // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
483 // All such elements have a "form" property.
484 if ( elem.parentNode && elem.disabled === false ) {
486 // Option elements defer to a parent optgroup if present
487 if ( "label" in elem ) {
488 if ( "label" in elem.parentNode ) {
489 return elem.parentNode.disabled === disabled;
491 return elem.disabled === disabled;
495 // Support: IE 6 - 11
496 // Use the isDisabled shortcut property to check for disabled fieldset ancestors
497 return elem.isDisabled === disabled ||
499 // Where there is no isDisabled, check manually
501 elem.isDisabled !== !disabled &&
502 disabledAncestor( elem ) === disabled;
505 return elem.disabled === disabled;
507 // Try to winnow out elements that can't be disabled before trusting the disabled property.
508 // Some victims get caught in our net (label, legend, menu, track), but it shouldn't
509 // even exist on them, let alone have a boolean value.
510 } else if ( "label" in elem ) {
511 return elem.disabled === disabled;
514 // Remaining elements are neither :enabled nor :disabled
520 * Returns a function to use in pseudos for positionals
521 * @param {Function} fn
523 function createPositionalPseudo( fn ) {
524 return markFunction(function( argument ) {
525 argument = +argument;
526 return markFunction(function( seed, matches ) {
528 matchIndexes = fn( [], seed.length, argument ),
529 i = matchIndexes.length;
531 // Match elements found at the specified indexes
533 if ( seed[ (j = matchIndexes[i]) ] ) {
534 seed[j] = !(matches[j] = seed[j]);
542 * Checks a node for validity as a Sizzle context
543 * @param {Element|Object=} context
544 * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
546 function testContext( context ) {
547 return context && typeof context.getElementsByTagName !== "undefined" && context;
550 // Expose support vars for convenience
551 support = Sizzle.support = {};
555 * @param {Element|Object} elem An element or a document
556 * @returns {Boolean} True iff elem is a non-HTML XML node
558 isXML = Sizzle.isXML = function( elem ) {
559 // documentElement is verified for cases where it doesn't yet exist
560 // (such as loading iframes in IE - #4833)
561 var documentElement = elem && (elem.ownerDocument || elem).documentElement;
562 return documentElement ? documentElement.nodeName !== "HTML" : false;
566 * Sets document-related variables once based on the current document
567 * @param {Element|Object} [doc] An element or document object to use to set the document
568 * @returns {Object} Returns the current document
570 setDocument = Sizzle.setDocument = function( node ) {
571 var hasCompare, subWindow,
572 doc = node ? node.ownerDocument || node : preferredDoc;
574 // Return early if doc is invalid or already selected
575 if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
579 // Update global variables
581 docElem = document.documentElement;
582 documentIsHTML = !isXML( document );
584 // Support: IE 9-11, Edge
585 // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
586 if ( preferredDoc !== document &&
587 (subWindow = document.defaultView) && subWindow.top !== subWindow ) {
589 // Support: IE 11, Edge
590 if ( subWindow.addEventListener ) {
591 subWindow.addEventListener( "unload", unloadHandler, false );
593 // Support: IE 9 - 10 only
594 } else if ( subWindow.attachEvent ) {
595 subWindow.attachEvent( "onunload", unloadHandler );
600 ---------------------------------------------------------------------- */
603 // Verify that getAttribute really returns attributes and not properties
604 // (excepting IE8 booleans)
605 support.attributes = assert(function( el ) {
607 return !el.getAttribute("className");
611 ---------------------------------------------------------------------- */
613 // Check if getElementsByTagName("*") returns only elements
614 support.getElementsByTagName = assert(function( el ) {
615 el.appendChild( document.createComment("") );
616 return !el.getElementsByTagName("*").length;
620 support.getElementsByClassName = rnative.test( document.getElementsByClassName );
623 // Check if getElementById returns elements by name
624 // The broken getElementById methods don't pick up programmatically-set names,
625 // so use a roundabout getElementsByName test
626 support.getById = assert(function( el ) {
627 docElem.appendChild( el ).id = expando;
628 return !document.getElementsByName || !document.getElementsByName( expando ).length;
631 // ID filter and find
632 if ( support.getById ) {
633 Expr.filter["ID"] = function( id ) {
634 var attrId = id.replace( runescape, funescape );
635 return function( elem ) {
636 return elem.getAttribute("id") === attrId;
639 Expr.find["ID"] = function( id, context ) {
640 if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
641 var elem = context.getElementById( id );
642 return elem ? [ elem ] : [];
646 Expr.filter["ID"] = function( id ) {
647 var attrId = id.replace( runescape, funescape );
648 return function( elem ) {
649 var node = typeof elem.getAttributeNode !== "undefined" &&
650 elem.getAttributeNode("id");
651 return node && node.value === attrId;
655 // Support: IE 6 - 7 only
656 // getElementById is not reliable as a find shortcut
657 Expr.find["ID"] = function( id, context ) {
658 if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
660 elem = context.getElementById( id );
664 // Verify the id attribute
665 node = elem.getAttributeNode("id");
666 if ( node && node.value === id ) {
670 // Fall back on getElementsByName
671 elems = context.getElementsByName( id );
673 while ( (elem = elems[i++]) ) {
674 node = elem.getAttributeNode("id");
675 if ( node && node.value === id ) {
687 Expr.find["TAG"] = support.getElementsByTagName ?
688 function( tag, context ) {
689 if ( typeof context.getElementsByTagName !== "undefined" ) {
690 return context.getElementsByTagName( tag );
692 // DocumentFragment nodes don't have gEBTN
693 } else if ( support.qsa ) {
694 return context.querySelectorAll( tag );
698 function( tag, context ) {
702 // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
703 results = context.getElementsByTagName( tag );
705 // Filter out possible comments
707 while ( (elem = results[i++]) ) {
708 if ( elem.nodeType === 1 ) {
719 Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
720 if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
721 return context.getElementsByClassName( className );
725 /* QSA/matchesSelector
726 ---------------------------------------------------------------------- */
728 // QSA and matchesSelector support
730 // matchesSelector(:active) reports false when true (IE9/Opera 11.5)
733 // qSa(:focus) reports false when true (Chrome 21)
734 // We allow this because of a bug in IE8/9 that throws an error
735 // whenever `document.activeElement` is accessed on an iframe
736 // So, we allow :focus to pass through QSA all the time to avoid the IE error
737 // See https://bugs.jquery.com/ticket/13378
740 if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
742 // Regex strategy adopted from Diego Perini
743 assert(function( el ) {
744 // Select is set to empty string on purpose
745 // This is to test IE's treatment of not explicitly
746 // setting a boolean content attribute,
747 // since its presence should be enough
748 // https://bugs.jquery.com/ticket/12359
749 docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" +
750 "<select id='" + expando + "-\r\\' msallowcapture=''>" +
751 "<option selected=''></option></select>";
753 // Support: IE8, Opera 11-12.16
754 // Nothing should be selected when empty strings follow ^= or $= or *=
755 // The test attribute must be unknown in Opera but "safe" for WinRT
756 // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
757 if ( el.querySelectorAll("[msallowcapture^='']").length ) {
758 rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
762 // Boolean attributes and "value" are not treated correctly
763 if ( !el.querySelectorAll("[selected]").length ) {
764 rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
767 // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
768 if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
769 rbuggyQSA.push("~=");
772 // Webkit/Opera - :checked should return selected option elements
773 // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
774 // IE8 throws error here and will not see later tests
775 if ( !el.querySelectorAll(":checked").length ) {
776 rbuggyQSA.push(":checked");
779 // Support: Safari 8+, iOS 8+
780 // https://bugs.webkit.org/show_bug.cgi?id=136851
781 // In-page `selector#id sibling-combinator selector` fails
782 if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {
783 rbuggyQSA.push(".#.+[+~]");
787 assert(function( el ) {
788 el.innerHTML = "<a href='' disabled='disabled'></a>" +
789 "<select disabled='disabled'><option/></select>";
791 // Support: Windows 8 Native Apps
792 // The type and name attributes are restricted during .innerHTML assignment
793 var input = document.createElement("input");
794 input.setAttribute( "type", "hidden" );
795 el.appendChild( input ).setAttribute( "name", "D" );
798 // Enforce case-sensitivity of name attribute
799 if ( el.querySelectorAll("[name=d]").length ) {
800 rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
803 // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
804 // IE8 throws error here and will not see later tests
805 if ( el.querySelectorAll(":enabled").length !== 2 ) {
806 rbuggyQSA.push( ":enabled", ":disabled" );
810 // IE's :disabled selector does not pick up the children of disabled fieldsets
811 docElem.appendChild( el ).disabled = true;
812 if ( el.querySelectorAll(":disabled").length !== 2 ) {
813 rbuggyQSA.push( ":enabled", ":disabled" );
816 // Opera 10-11 does not throw on post-comma invalid pseudos
817 el.querySelectorAll("*,:x");
818 rbuggyQSA.push(",.*:");
822 if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
823 docElem.webkitMatchesSelector ||
824 docElem.mozMatchesSelector ||
825 docElem.oMatchesSelector ||
826 docElem.msMatchesSelector) )) ) {
828 assert(function( el ) {
829 // Check to see if it's possible to do matchesSelector
830 // on a disconnected node (IE 9)
831 support.disconnectedMatch = matches.call( el, "*" );
833 // This should fail with an exception
834 // Gecko does not error, returns false instead
835 matches.call( el, "[s!='']:x" );
836 rbuggyMatches.push( "!=", pseudos );
840 rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
841 rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
844 ---------------------------------------------------------------------- */
845 hasCompare = rnative.test( docElem.compareDocumentPosition );
847 // Element contains another
848 // Purposefully self-exclusive
849 // As in, an element does not contain itself
850 contains = hasCompare || rnative.test( docElem.contains ) ?
852 var adown = a.nodeType === 9 ? a.documentElement : a,
853 bup = b && b.parentNode;
854 return a === bup || !!( bup && bup.nodeType === 1 && (
856 adown.contains( bup ) :
857 a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
862 while ( (b = b.parentNode) ) {
872 ---------------------------------------------------------------------- */
874 // Document order sorting
875 sortOrder = hasCompare ?
878 // Flag for duplicate removal
884 // Sort on method existence if only one input has compareDocumentPosition
885 var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
890 // Calculate position if both inputs belong to the same document
891 compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
892 a.compareDocumentPosition( b ) :
894 // Otherwise we know they are disconnected
897 // Disconnected nodes
899 (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
901 // Choose the first element that is related to our preferred document
902 if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
905 if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
909 // Maintain original order
911 ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
915 return compare & 4 ? -1 : 1;
918 // Exit early if the nodes are identical
931 // Parentless nodes are either documents or disconnected
932 if ( !aup || !bup ) {
933 return a === document ? -1 :
938 ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
941 // If the nodes are siblings, we can do a quick check
942 } else if ( aup === bup ) {
943 return siblingCheck( a, b );
946 // Otherwise we need full lists of their ancestors for comparison
948 while ( (cur = cur.parentNode) ) {
952 while ( (cur = cur.parentNode) ) {
956 // Walk down the tree looking for a discrepancy
957 while ( ap[i] === bp[i] ) {
962 // Do a sibling check if the nodes have a common ancestor
963 siblingCheck( ap[i], bp[i] ) :
965 // Otherwise nodes in our document sort first
966 ap[i] === preferredDoc ? -1 :
967 bp[i] === preferredDoc ? 1 :
974 Sizzle.matches = function( expr, elements ) {
975 return Sizzle( expr, null, null, elements );
978 Sizzle.matchesSelector = function( elem, expr ) {
979 // Set document vars if needed
980 if ( ( elem.ownerDocument || elem ) !== document ) {
984 // Make sure that attribute selectors are quoted
985 expr = expr.replace( rattributeQuotes, "='$1']" );
987 if ( support.matchesSelector && documentIsHTML &&
988 !compilerCache[ expr + " " ] &&
989 ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
990 ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
993 var ret = matches.call( elem, expr );
995 // IE 9's matchesSelector returns false on disconnected nodes
996 if ( ret || support.disconnectedMatch ||
997 // As well, disconnected nodes are said to be in a document
999 elem.document && elem.document.nodeType !== 11 ) {
1005 return Sizzle( expr, document, null, [ elem ] ).length > 0;
1008 Sizzle.contains = function( context, elem ) {
1009 // Set document vars if needed
1010 if ( ( context.ownerDocument || context ) !== document ) {
1011 setDocument( context );
1013 return contains( context, elem );
1016 Sizzle.attr = function( elem, name ) {
1017 // Set document vars if needed
1018 if ( ( elem.ownerDocument || elem ) !== document ) {
1019 setDocument( elem );
1022 var fn = Expr.attrHandle[ name.toLowerCase() ],
1023 // Don't get fooled by Object.prototype properties (jQuery #13807)
1024 val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
1025 fn( elem, name, !documentIsHTML ) :
1028 return val !== undefined ?
1030 support.attributes || !documentIsHTML ?
1031 elem.getAttribute( name ) :
1032 (val = elem.getAttributeNode(name)) && val.specified ?
1037 Sizzle.escape = function( sel ) {
1038 return (sel + "").replace( rcssescape, fcssescape );
1041 Sizzle.error = function( msg ) {
1042 throw new Error( "Syntax error, unrecognized expression: " + msg );
1046 * Document sorting and removing duplicates
1047 * @param {ArrayLike} results
1049 Sizzle.uniqueSort = function( results ) {
1055 // Unless we *know* we can detect duplicates, assume their presence
1056 hasDuplicate = !support.detectDuplicates;
1057 sortInput = !support.sortStable && results.slice( 0 );
1058 results.sort( sortOrder );
1060 if ( hasDuplicate ) {
1061 while ( (elem = results[i++]) ) {
1062 if ( elem === results[ i ] ) {
1063 j = duplicates.push( i );
1067 results.splice( duplicates[ j ], 1 );
1071 // Clear input after sorting to release objects
1072 // See https://github.com/jquery/sizzle/pull/225
1079 * Utility function for retrieving the text value of an array of DOM nodes
1080 * @param {Array|Element} elem
1082 getText = Sizzle.getText = function( elem ) {
1086 nodeType = elem.nodeType;
1089 // If no nodeType, this is expected to be an array
1090 while ( (node = elem[i++]) ) {
1091 // Do not traverse comment nodes
1092 ret += getText( node );
1094 } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
1095 // Use textContent for elements
1096 // innerText usage removed for consistency of new lines (jQuery #11153)
1097 if ( typeof elem.textContent === "string" ) {
1098 return elem.textContent;
1100 // Traverse its children
1101 for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
1102 ret += getText( elem );
1105 } else if ( nodeType === 3 || nodeType === 4 ) {
1106 return elem.nodeValue;
1108 // Do not include comment or processing instruction nodes
1113 Expr = Sizzle.selectors = {
1115 // Can be adjusted by the user
1118 createPseudo: markFunction,
1127 ">": { dir: "parentNode", first: true },
1128 " ": { dir: "parentNode" },
1129 "+": { dir: "previousSibling", first: true },
1130 "~": { dir: "previousSibling" }
1134 "ATTR": function( match ) {
1135 match[1] = match[1].replace( runescape, funescape );
1137 // Move the given value to match[3] whether quoted or unquoted
1138 match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
1140 if ( match[2] === "~=" ) {
1141 match[3] = " " + match[3] + " ";
1144 return match.slice( 0, 4 );
1147 "CHILD": function( match ) {
1148 /* matches from matchExpr["CHILD"]
1149 1 type (only|nth|...)
1150 2 what (child|of-type)
1151 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
1152 4 xn-component of xn+y argument ([+-]?\d*n|)
1153 5 sign of xn-component
1155 7 sign of y-component
1158 match[1] = match[1].toLowerCase();
1160 if ( match[1].slice( 0, 3 ) === "nth" ) {
1161 // nth-* requires argument
1163 Sizzle.error( match[0] );
1166 // numeric x and y parameters for Expr.filter.CHILD
1167 // remember that false/true cast respectively to 0/1
1168 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
1169 match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
1171 // other types prohibit arguments
1172 } else if ( match[3] ) {
1173 Sizzle.error( match[0] );
1179 "PSEUDO": function( match ) {
1181 unquoted = !match[6] && match[2];
1183 if ( matchExpr["CHILD"].test( match[0] ) ) {
1187 // Accept quoted arguments as-is
1189 match[2] = match[4] || match[5] || "";
1191 // Strip excess characters from unquoted arguments
1192 } else if ( unquoted && rpseudo.test( unquoted ) &&
1193 // Get excess from tokenize (recursively)
1194 (excess = tokenize( unquoted, true )) &&
1195 // advance to the next closing parenthesis
1196 (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
1198 // excess is a negative index
1199 match[0] = match[0].slice( 0, excess );
1200 match[2] = unquoted.slice( 0, excess );
1203 // Return only captures needed by the pseudo filter method (type and argument)
1204 return match.slice( 0, 3 );
1210 "TAG": function( nodeNameSelector ) {
1211 var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
1212 return nodeNameSelector === "*" ?
1213 function() { return true; } :
1215 return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
1219 "CLASS": function( className ) {
1220 var pattern = classCache[ className + " " ];
1223 (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
1224 classCache( className, function( elem ) {
1225 return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
1229 "ATTR": function( name, operator, check ) {
1230 return function( elem ) {
1231 var result = Sizzle.attr( elem, name );
1233 if ( result == null ) {
1234 return operator === "!=";
1242 return operator === "=" ? result === check :
1243 operator === "!=" ? result !== check :
1244 operator === "^=" ? check && result.indexOf( check ) === 0 :
1245 operator === "*=" ? check && result.indexOf( check ) > -1 :
1246 operator === "$=" ? check && result.slice( -check.length ) === check :
1247 operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
1248 operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
1253 "CHILD": function( type, what, argument, first, last ) {
1254 var simple = type.slice( 0, 3 ) !== "nth",
1255 forward = type.slice( -4 ) !== "last",
1256 ofType = what === "of-type";
1258 return first === 1 && last === 0 ?
1260 // Shortcut for :nth-*(n)
1262 return !!elem.parentNode;
1265 function( elem, context, xml ) {
1266 var cache, uniqueCache, outerCache, node, nodeIndex, start,
1267 dir = simple !== forward ? "nextSibling" : "previousSibling",
1268 parent = elem.parentNode,
1269 name = ofType && elem.nodeName.toLowerCase(),
1270 useCache = !xml && !ofType,
1275 // :(first|last|only)-(child|of-type)
1279 while ( (node = node[ dir ]) ) {
1281 node.nodeName.toLowerCase() === name :
1282 node.nodeType === 1 ) {
1287 // Reverse direction for :only-* (if we haven't yet done so)
1288 start = dir = type === "only" && !start && "nextSibling";
1293 start = [ forward ? parent.firstChild : parent.lastChild ];
1295 // non-xml :nth-child(...) stores cache data on `parent`
1296 if ( forward && useCache ) {
1298 // Seek `elem` from a previously-cached index
1300 // ...in a gzip-friendly way
1302 outerCache = node[ expando ] || (node[ expando ] = {});
1304 // Support: IE <9 only
1305 // Defend against cloned attroperties (jQuery gh-1709)
1306 uniqueCache = outerCache[ node.uniqueID ] ||
1307 (outerCache[ node.uniqueID ] = {});
1309 cache = uniqueCache[ type ] || [];
1310 nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
1311 diff = nodeIndex && cache[ 2 ];
1312 node = nodeIndex && parent.childNodes[ nodeIndex ];
1314 while ( (node = ++nodeIndex && node && node[ dir ] ||
1316 // Fallback to seeking `elem` from the start
1317 (diff = nodeIndex = 0) || start.pop()) ) {
1319 // When found, cache indexes on `parent` and break
1320 if ( node.nodeType === 1 && ++diff && node === elem ) {
1321 uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
1327 // Use previously-cached element index if available
1329 // ...in a gzip-friendly way
1331 outerCache = node[ expando ] || (node[ expando ] = {});
1333 // Support: IE <9 only
1334 // Defend against cloned attroperties (jQuery gh-1709)
1335 uniqueCache = outerCache[ node.uniqueID ] ||
1336 (outerCache[ node.uniqueID ] = {});
1338 cache = uniqueCache[ type ] || [];
1339 nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
1343 // xml :nth-child(...)
1344 // or :nth-last-child(...) or :nth(-last)?-of-type(...)
1345 if ( diff === false ) {
1346 // Use the same loop as above to seek `elem` from the start
1347 while ( (node = ++nodeIndex && node && node[ dir ] ||
1348 (diff = nodeIndex = 0) || start.pop()) ) {
1351 node.nodeName.toLowerCase() === name :
1352 node.nodeType === 1 ) &&
1355 // Cache the index of each encountered element
1357 outerCache = node[ expando ] || (node[ expando ] = {});
1359 // Support: IE <9 only
1360 // Defend against cloned attroperties (jQuery gh-1709)
1361 uniqueCache = outerCache[ node.uniqueID ] ||
1362 (outerCache[ node.uniqueID ] = {});
1364 uniqueCache[ type ] = [ dirruns, diff ];
1367 if ( node === elem ) {
1375 // Incorporate the offset, then check against cycle size
1377 return diff === first || ( diff % first === 0 && diff / first >= 0 );
1382 "PSEUDO": function( pseudo, argument ) {
1383 // pseudo-class names are case-insensitive
1384 // http://www.w3.org/TR/selectors/#pseudo-classes
1385 // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
1386 // Remember that setFilters inherits from pseudos
1388 fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
1389 Sizzle.error( "unsupported pseudo: " + pseudo );
1391 // The user may use createPseudo to indicate that
1392 // arguments are needed to create the filter function
1393 // just as Sizzle does
1394 if ( fn[ expando ] ) {
1395 return fn( argument );
1398 // But maintain support for old signatures
1399 if ( fn.length > 1 ) {
1400 args = [ pseudo, pseudo, "", argument ];
1401 return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
1402 markFunction(function( seed, matches ) {
1404 matched = fn( seed, argument ),
1407 idx = indexOf( seed, matched[i] );
1408 seed[ idx ] = !( matches[ idx ] = matched[i] );
1412 return fn( elem, 0, args );
1421 // Potentially complex pseudos
1422 "not": markFunction(function( selector ) {
1423 // Trim the selector passed to compile
1424 // to avoid treating leading and trailing
1425 // spaces as combinators
1428 matcher = compile( selector.replace( rtrim, "$1" ) );
1430 return matcher[ expando ] ?
1431 markFunction(function( seed, matches, context, xml ) {
1433 unmatched = matcher( seed, null, xml, [] ),
1436 // Match elements unmatched by `matcher`
1438 if ( (elem = unmatched[i]) ) {
1439 seed[i] = !(matches[i] = elem);
1443 function( elem, context, xml ) {
1445 matcher( input, null, xml, results );
1446 // Don't keep the element (issue #299)
1448 return !results.pop();
1452 "has": markFunction(function( selector ) {
1453 return function( elem ) {
1454 return Sizzle( selector, elem ).length > 0;
1458 "contains": markFunction(function( text ) {
1459 text = text.replace( runescape, funescape );
1460 return function( elem ) {
1461 return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
1465 // "Whether an element is represented by a :lang() selector
1466 // is based solely on the element's language value
1467 // being equal to the identifier C,
1468 // or beginning with the identifier C immediately followed by "-".
1469 // The matching of C against the element's language value is performed case-insensitively.
1470 // The identifier C does not have to be a valid language name."
1471 // http://www.w3.org/TR/selectors/#lang-pseudo
1472 "lang": markFunction( function( lang ) {
1473 // lang value must be a valid identifier
1474 if ( !ridentifier.test(lang || "") ) {
1475 Sizzle.error( "unsupported lang: " + lang );
1477 lang = lang.replace( runescape, funescape ).toLowerCase();
1478 return function( elem ) {
1481 if ( (elemLang = documentIsHTML ?
1483 elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
1485 elemLang = elemLang.toLowerCase();
1486 return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
1488 } while ( (elem = elem.parentNode) && elem.nodeType === 1 );
1494 "target": function( elem ) {
1495 var hash = window.location && window.location.hash;
1496 return hash && hash.slice( 1 ) === elem.id;
1499 "root": function( elem ) {
1500 return elem === docElem;
1503 "focus": function( elem ) {
1504 return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
1507 // Boolean properties
1508 "enabled": createDisabledPseudo( false ),
1509 "disabled": createDisabledPseudo( true ),
1511 "checked": function( elem ) {
1512 // In CSS3, :checked should return both checked and selected elements
1513 // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
1514 var nodeName = elem.nodeName.toLowerCase();
1515 return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
1518 "selected": function( elem ) {
1519 // Accessing this property makes selected-by-default
1520 // options in Safari work properly
1521 if ( elem.parentNode ) {
1522 elem.parentNode.selectedIndex;
1525 return elem.selected === true;
1529 "empty": function( elem ) {
1530 // http://www.w3.org/TR/selectors/#empty-pseudo
1531 // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
1532 // but not by others (comment: 8; processing instruction: 7; etc.)
1533 // nodeType < 6 works because attributes (2) do not appear as children
1534 for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
1535 if ( elem.nodeType < 6 ) {
1542 "parent": function( elem ) {
1543 return !Expr.pseudos["empty"]( elem );
1546 // Element/input types
1547 "header": function( elem ) {
1548 return rheader.test( elem.nodeName );
1551 "input": function( elem ) {
1552 return rinputs.test( elem.nodeName );
1555 "button": function( elem ) {
1556 var name = elem.nodeName.toLowerCase();
1557 return name === "input" && elem.type === "button" || name === "button";
1560 "text": function( elem ) {
1562 return elem.nodeName.toLowerCase() === "input" &&
1563 elem.type === "text" &&
1566 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
1567 ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
1570 // Position-in-collection
1571 "first": createPositionalPseudo(function() {
1575 "last": createPositionalPseudo(function( matchIndexes, length ) {
1576 return [ length - 1 ];
1579 "eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
1580 return [ argument < 0 ? argument + length : argument ];
1583 "even": createPositionalPseudo(function( matchIndexes, length ) {
1585 for ( ; i < length; i += 2 ) {
1586 matchIndexes.push( i );
1588 return matchIndexes;
1591 "odd": createPositionalPseudo(function( matchIndexes, length ) {
1593 for ( ; i < length; i += 2 ) {
1594 matchIndexes.push( i );
1596 return matchIndexes;
1599 "lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
1600 var i = argument < 0 ? argument + length : argument;
1601 for ( ; --i >= 0; ) {
1602 matchIndexes.push( i );
1604 return matchIndexes;
1607 "gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
1608 var i = argument < 0 ? argument + length : argument;
1609 for ( ; ++i < length; ) {
1610 matchIndexes.push( i );
1612 return matchIndexes;
1617 Expr.pseudos["nth"] = Expr.pseudos["eq"];
1619 // Add button/input type pseudos
1620 for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
1621 Expr.pseudos[ i ] = createInputPseudo( i );
1623 for ( i in { submit: true, reset: true } ) {
1624 Expr.pseudos[ i ] = createButtonPseudo( i );
1627 // Easy API for creating new setFilters
1628 function setFilters() {}
1629 setFilters.prototype = Expr.filters = Expr.pseudos;
1630 Expr.setFilters = new setFilters();
1632 tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
1633 var matched, match, tokens, type,
1634 soFar, groups, preFilters,
1635 cached = tokenCache[ selector + " " ];
1638 return parseOnly ? 0 : cached.slice( 0 );
1643 preFilters = Expr.preFilter;
1647 // Comma and first run
1648 if ( !matched || (match = rcomma.exec( soFar )) ) {
1650 // Don't consume trailing commas as valid
1651 soFar = soFar.slice( match[0].length ) || soFar;
1653 groups.push( (tokens = []) );
1659 if ( (match = rcombinators.exec( soFar )) ) {
1660 matched = match.shift();
1663 // Cast descendant combinators to space
1664 type: match[0].replace( rtrim, " " )
1666 soFar = soFar.slice( matched.length );
1670 for ( type in Expr.filter ) {
1671 if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
1672 (match = preFilters[ type ]( match ))) ) {
1673 matched = match.shift();
1679 soFar = soFar.slice( matched.length );
1688 // Return the length of the invalid excess
1689 // if we're just parsing
1690 // Otherwise, throw an error or return tokens
1694 Sizzle.error( selector ) :
1696 tokenCache( selector, groups ).slice( 0 );
1699 function toSelector( tokens ) {
1701 len = tokens.length,
1703 for ( ; i < len; i++ ) {
1704 selector += tokens[i].value;
1709 function addCombinator( matcher, combinator, base ) {
1710 var dir = combinator.dir,
1711 skip = combinator.next,
1713 checkNonElements = base && key === "parentNode",
1716 return combinator.first ?
1717 // Check against closest ancestor/preceding element
1718 function( elem, context, xml ) {
1719 while ( (elem = elem[ dir ]) ) {
1720 if ( elem.nodeType === 1 || checkNonElements ) {
1721 return matcher( elem, context, xml );
1727 // Check against all ancestor/preceding elements
1728 function( elem, context, xml ) {
1729 var oldCache, uniqueCache, outerCache,
1730 newCache = [ dirruns, doneName ];
1732 // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
1734 while ( (elem = elem[ dir ]) ) {
1735 if ( elem.nodeType === 1 || checkNonElements ) {
1736 if ( matcher( elem, context, xml ) ) {
1742 while ( (elem = elem[ dir ]) ) {
1743 if ( elem.nodeType === 1 || checkNonElements ) {
1744 outerCache = elem[ expando ] || (elem[ expando ] = {});
1746 // Support: IE <9 only
1747 // Defend against cloned attroperties (jQuery gh-1709)
1748 uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
1750 if ( skip && skip === elem.nodeName.toLowerCase() ) {
1751 elem = elem[ dir ] || elem;
1752 } else if ( (oldCache = uniqueCache[ key ]) &&
1753 oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
1755 // Assign to newCache so results back-propagate to previous elements
1756 return (newCache[ 2 ] = oldCache[ 2 ]);
1758 // Reuse newcache so results back-propagate to previous elements
1759 uniqueCache[ key ] = newCache;
1761 // A match means we're done; a fail means we have to keep checking
1762 if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
1773 function elementMatcher( matchers ) {
1774 return matchers.length > 1 ?
1775 function( elem, context, xml ) {
1776 var i = matchers.length;
1778 if ( !matchers[i]( elem, context, xml ) ) {
1787 function multipleContexts( selector, contexts, results ) {
1789 len = contexts.length;
1790 for ( ; i < len; i++ ) {
1791 Sizzle( selector, contexts[i], results );
1796 function condense( unmatched, map, filter, context, xml ) {
1800 len = unmatched.length,
1801 mapped = map != null;
1803 for ( ; i < len; i++ ) {
1804 if ( (elem = unmatched[i]) ) {
1805 if ( !filter || filter( elem, context, xml ) ) {
1806 newUnmatched.push( elem );
1814 return newUnmatched;
1817 function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
1818 if ( postFilter && !postFilter[ expando ] ) {
1819 postFilter = setMatcher( postFilter );
1821 if ( postFinder && !postFinder[ expando ] ) {
1822 postFinder = setMatcher( postFinder, postSelector );
1824 return markFunction(function( seed, results, context, xml ) {
1828 preexisting = results.length,
1830 // Get initial elements from seed or context
1831 elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
1833 // Prefilter to get matcher input, preserving a map for seed-results synchronization
1834 matcherIn = preFilter && ( seed || !selector ) ?
1835 condense( elems, preMap, preFilter, context, xml ) :
1838 matcherOut = matcher ?
1839 // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
1840 postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
1842 // ...intermediate processing is necessary
1845 // ...otherwise use results directly
1849 // Find primary matches
1851 matcher( matcherIn, matcherOut, context, xml );
1856 temp = condense( matcherOut, postMap );
1857 postFilter( temp, [], context, xml );
1859 // Un-match failing elements by moving them back to matcherIn
1862 if ( (elem = temp[i]) ) {
1863 matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
1869 if ( postFinder || preFilter ) {
1871 // Get the final matcherOut by condensing this intermediate into postFinder contexts
1873 i = matcherOut.length;
1875 if ( (elem = matcherOut[i]) ) {
1876 // Restore matcherIn since elem is not yet a final match
1877 temp.push( (matcherIn[i] = elem) );
1880 postFinder( null, (matcherOut = []), temp, xml );
1883 // Move matched elements from seed to results to keep them synchronized
1884 i = matcherOut.length;
1886 if ( (elem = matcherOut[i]) &&
1887 (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
1889 seed[temp] = !(results[temp] = elem);
1894 // Add elements to results, through postFinder if defined
1896 matcherOut = condense(
1897 matcherOut === results ?
1898 matcherOut.splice( preexisting, matcherOut.length ) :
1902 postFinder( null, results, matcherOut, xml );
1904 push.apply( results, matcherOut );
1910 function matcherFromTokens( tokens ) {
1911 var checkContext, matcher, j,
1912 len = tokens.length,
1913 leadingRelative = Expr.relative[ tokens[0].type ],
1914 implicitRelative = leadingRelative || Expr.relative[" "],
1915 i = leadingRelative ? 1 : 0,
1917 // The foundational matcher ensures that elements are reachable from top-level context(s)
1918 matchContext = addCombinator( function( elem ) {
1919 return elem === checkContext;
1920 }, implicitRelative, true ),
1921 matchAnyContext = addCombinator( function( elem ) {
1922 return indexOf( checkContext, elem ) > -1;
1923 }, implicitRelative, true ),
1924 matchers = [ function( elem, context, xml ) {
1925 var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
1926 (checkContext = context).nodeType ?
1927 matchContext( elem, context, xml ) :
1928 matchAnyContext( elem, context, xml ) );
1929 // Avoid hanging onto element (issue #299)
1930 checkContext = null;
1934 for ( ; i < len; i++ ) {
1935 if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
1936 matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
1938 matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
1940 // Return special upon seeing a positional matcher
1941 if ( matcher[ expando ] ) {
1942 // Find the next relative operator (if any) for proper handling
1944 for ( ; j < len; j++ ) {
1945 if ( Expr.relative[ tokens[j].type ] ) {
1950 i > 1 && elementMatcher( matchers ),
1951 i > 1 && toSelector(
1952 // If the preceding token was a descendant combinator, insert an implicit any-element `*`
1953 tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
1954 ).replace( rtrim, "$1" ),
1956 i < j && matcherFromTokens( tokens.slice( i, j ) ),
1957 j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
1958 j < len && toSelector( tokens )
1961 matchers.push( matcher );
1965 return elementMatcher( matchers );
1968 function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
1969 var bySet = setMatchers.length > 0,
1970 byElement = elementMatchers.length > 0,
1971 superMatcher = function( seed, context, xml, results, outermost ) {
1972 var elem, j, matcher,
1975 unmatched = seed && [],
1977 contextBackup = outermostContext,
1978 // We must always have either seed elements or outermost context
1979 elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
1980 // Use integer dirruns iff this is the outermost matcher
1981 dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
1985 outermostContext = context === document || context || outermost;
1988 // Add elements passing elementMatchers directly to results
1989 // Support: IE<9, Safari
1990 // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
1991 for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
1992 if ( byElement && elem ) {
1994 if ( !context && elem.ownerDocument !== document ) {
1995 setDocument( elem );
1996 xml = !documentIsHTML;
1998 while ( (matcher = elementMatchers[j++]) ) {
1999 if ( matcher( elem, context || document, xml) ) {
2000 results.push( elem );
2005 dirruns = dirrunsUnique;
2009 // Track unmatched elements for set filters
2011 // They will have gone through all possible matchers
2012 if ( (elem = !matcher && elem) ) {
2016 // Lengthen the array for every element, matched or not
2018 unmatched.push( elem );
2023 // `i` is now the count of elements visited above, and adding it to `matchedCount`
2024 // makes the latter nonnegative.
2027 // Apply set filters to unmatched elements
2028 // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
2029 // equals `i`), unless we didn't visit _any_ elements in the above loop because we have
2030 // no element matchers and no seed.
2031 // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
2032 // case, which will result in a "00" `matchedCount` that differs from `i` but is also
2033 // numerically zero.
2034 if ( bySet && i !== matchedCount ) {
2036 while ( (matcher = setMatchers[j++]) ) {
2037 matcher( unmatched, setMatched, context, xml );
2041 // Reintegrate element matches to eliminate the need for sorting
2042 if ( matchedCount > 0 ) {
2044 if ( !(unmatched[i] || setMatched[i]) ) {
2045 setMatched[i] = pop.call( results );
2050 // Discard index placeholder values to get only actual matches
2051 setMatched = condense( setMatched );
2054 // Add matches to results
2055 push.apply( results, setMatched );
2057 // Seedless set matches succeeding multiple successful matchers stipulate sorting
2058 if ( outermost && !seed && setMatched.length > 0 &&
2059 ( matchedCount + setMatchers.length ) > 1 ) {
2061 Sizzle.uniqueSort( results );
2065 // Override manipulation of globals by nested matchers
2067 dirruns = dirrunsUnique;
2068 outermostContext = contextBackup;
2075 markFunction( superMatcher ) :
2079 compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
2082 elementMatchers = [],
2083 cached = compilerCache[ selector + " " ];
2086 // Generate a function of recursive functions that can be used to check each element
2088 match = tokenize( selector );
2092 cached = matcherFromTokens( match[i] );
2093 if ( cached[ expando ] ) {
2094 setMatchers.push( cached );
2096 elementMatchers.push( cached );
2100 // Cache the compiled function
2101 cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
2103 // Save selector and tokenization
2104 cached.selector = selector;
2110 * A low-level selection function that works with Sizzle's compiled
2111 * selector functions
2112 * @param {String|Function} selector A selector or a pre-compiled
2113 * selector function built with Sizzle.compile
2114 * @param {Element} context
2115 * @param {Array} [results]
2116 * @param {Array} [seed] A set of elements to match against
2118 select = Sizzle.select = function( selector, context, results, seed ) {
2119 var i, tokens, token, type, find,
2120 compiled = typeof selector === "function" && selector,
2121 match = !seed && tokenize( (selector = compiled.selector || selector) );
2123 results = results || [];
2125 // Try to minimize operations if there is only one selector in the list and no seed
2126 // (the latter of which guarantees us context)
2127 if ( match.length === 1 ) {
2129 // Reduce context if the leading compound selector is an ID
2130 tokens = match[0] = match[0].slice( 0 );
2131 if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
2132 context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) {
2134 context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
2138 // Precompiled matchers will still verify ancestry, so step up a level
2139 } else if ( compiled ) {
2140 context = context.parentNode;
2143 selector = selector.slice( tokens.shift().value.length );
2146 // Fetch a seed set for right-to-left matching
2147 i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
2151 // Abort if we hit a combinator
2152 if ( Expr.relative[ (type = token.type) ] ) {
2155 if ( (find = Expr.find[ type ]) ) {
2156 // Search, expanding context for leading sibling combinators
2158 token.matches[0].replace( runescape, funescape ),
2159 rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
2162 // If seed is empty or no tokens remain, we can return early
2163 tokens.splice( i, 1 );
2164 selector = seed.length && toSelector( tokens );
2166 push.apply( results, seed );
2176 // Compile and execute a filtering function if one is not provided
2177 // Provide `match` to avoid retokenization if we modified the selector above
2178 ( compiled || compile( selector, match ) )(
2183 !context || rsibling.test( selector ) && testContext( context.parentNode ) || context
2188 // One-time assignments
2191 support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
2193 // Support: Chrome 14-35+
2194 // Always assume duplicates if they aren't passed to the comparison function
2195 support.detectDuplicates = !!hasDuplicate;
2197 // Initialize against the default document
2200 // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
2201 // Detached nodes confoundingly follow *each other*
2202 support.sortDetached = assert(function( el ) {
2203 // Should return 1, but returns 4 (following)
2204 return el.compareDocumentPosition( document.createElement("fieldset") ) & 1;
2208 // Prevent attribute/property "interpolation"
2209 // https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
2210 if ( !assert(function( el ) {
2211 el.innerHTML = "<a href='#'></a>";
2212 return el.firstChild.getAttribute("href") === "#" ;
2214 addHandle( "type|href|height|width", function( elem, name, isXML ) {
2216 return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
2222 // Use defaultValue in place of getAttribute("value")
2223 if ( !support.attributes || !assert(function( el ) {
2224 el.innerHTML = "<input/>";
2225 el.firstChild.setAttribute( "value", "" );
2226 return el.firstChild.getAttribute( "value" ) === "";
2228 addHandle( "value", function( elem, name, isXML ) {
2229 if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
2230 return elem.defaultValue;
2236 // Use getAttributeNode to fetch booleans when getAttribute lies
2237 if ( !assert(function( el ) {
2238 return el.getAttribute("disabled") == null;
2240 addHandle( booleans, function( elem, name, isXML ) {
2243 return elem[ name ] === true ? name.toLowerCase() :
2244 (val = elem.getAttributeNode( name )) && val.specified ?
2252 var _sizzle = window.Sizzle;
2254 Sizzle.noConflict = function() {
2255 if ( window.Sizzle === Sizzle ) {
2256 window.Sizzle = _sizzle;
2262 if ( typeof define === "function" && define.amd ) {
2263 define(function() { return Sizzle; });
2264 // Sizzle requires that there be a global window in Common-JS like environments
2265 } else if ( typeof module !== "undefined" && module.exports ) {
2266 module.exports = Sizzle;
2268 window.Sizzle = Sizzle;