Last active
October 12, 2015 00:46
-
-
Save tylucaskelley/bfed45af9567dec73f56 to your computer and use it in GitHub Desktop.
Udacity jQuery Webcast: How Sizzle Works Internally
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Let's say you give this to jQuery on a browser that doesn't support the selectors API | |
var $element = $(".title p"); | |
// First, Sizzle will break up the query into an array of selectors: | |
[".title", "p"] | |
// You might think that Sizzle will go left to right to find our elements! | |
// Actually, it does the opposite; Sizzle will first try to find all of the "a" tags, | |
// using it's "find" method. | |
// "find" makes use of a lot of regular expressions to look for tags, | |
// classes, IDs, etc: | |
match: { | |
ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, | |
CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/, | |
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/, | |
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, | |
TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/, | |
CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, | |
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, | |
PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ | |
} | |
// in the case of "a", it'll match under the match.TAG regex. | |
// now that Sizzle knows it's looking for a tag, it'll call the | |
// appropriate function to grab it: | |
context.getElementsByTagName(selector); | |
// "context" generally defaults to the entire document. | |
// "selector" is "a" here. | |
// Sizzle will then go to the previous element in it's array | |
// and filter out any "a" tags that don't have an element with | |
// the ".title" class on it. | |
// So to wrap up, Sizzle starts at the inner-most element, creating an array | |
// of matches that gradually gets smaller as we filter out parent elements that | |
// don't match what was asked for in the selector string. | |
// Check out the source code here to see it for yourself! | |
// https://github.com/jquery/sizzle/blob/master/src/sizzle.js |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment