Internal Mechanics of jQuery: Prototype Setup and Selector Parsing

Prototype Object Definition and Constructor Restoration

At the core of the library's architecture lies the assignment of the prototype object. The code snippet below demonstrates how jQuery.fn serves as an alias for jQuery.prototype. When an object literal is assigned to the prototype, it completely overwrites the default structure provided by JavaScript.

jQuery.fn = jQuery.prototype = {
    // Stores the current library version
    jquery: "3.0.0", 

    // Explicitly reset the constructor property to point back to the main function
    constructor: jQuery,

    init: function(target, context, rootjQuery) {
        var patternMatch, element;

        // Scenario: $(""), $(null), $(undefined), $(false)
        if (!target) {
            return this;
        }
        // ... rest of the logic
    }
};

Because overwriting the prototype severs the link between the instance and its original constructor, the code manually reassigns constructor: jQuery. Without this step, instances would incorrectly report Object as their constructor. The property jquery is simply a string revealing the running version.

var instance = new jQuery();
console.log(instance.jquery); // Output: "3.0.0"

The Initialization Logic

The init function serves as the actual constructor within the public facade. It begins by defining local variables and immediately checking for falsy inputs.

init: function(target, context, rootjQuery) {
    var matchResult, element;

    // HANDLE: $(""), $(null), $(undefined), $(false)
    if (!target) {
        return this;
    }
    // ...
}

The first parameter, target (often called selector in other contexts), is the primary input. The condition if (!target) captures scenarios where the input is an empty string, null, undefined, or false. In these cases, the function halts executionn and returns this, which refers to the prototype object, effectively providing an empty jQuery object.

Processing String Arguments

When the input passes the initial check and is confirmed to be a string, the logic branches to determine if it represents an HTML fragment or a standard CSS selector.

// Handle HTML strings
if (typeof target === 'string') {
    const firstChar = target[0];
    const lastChar = target[target.length - 1];

    // Optimization: Detect strings that look like single HTML tags
    // Example: <a>, <div>, <span>
    if (
        firstChar === '<' && 
        lastChar === '>' && 
        target.length >= 3
    ) {
        // Assume the string is HTML and skip the regex check
        matchResult = [null, target, null];
    } else {
        // Use regex for complex selectors or IDs
        matchResult = rquickExpr.exec(target);
    }
}

<p>This section uses a heuristic to optimize performance. If the string starts with <, ends with >, and has a length of at least 3, it is presumed to be an HTML tag. This bypasses the overhead of a regular expression execution for simple cases like <a>. For all other strings, the engine falls back to the rquickExpr regular expression.</p>

<h2>Regular Expression Breakdown</h2>

<p>The exec() method returns either an array containing match details or null if no match is found. The logic relies on the specific regex pattern defined as rquickExpr:</p>

rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/

<p>This pattern is designed to match HTML fragments or ID selectors. Here is the token breakdown:</p>

<ul>
    <li>^ and $: Anchors that ensure the match spans the entire string.</li>
    <li>(?: ... ): A non-capturing group used to group alternatives without storing the match for back-referencing, saving memory.</li>
    <li>\s*: Matches zero or more whitespace characters at the start. This allows inputs like $(' <div>') to work correctly.</li>
    <li>(<[\w\W]+>): The first capturing group. It matches a less-than sign, followed by one or more word or non-word characters (any character), and a greater-than sign. This captures tags like <div>.</li>
    <li>[^>]*: Matches any character that is not a greater-than sign, zero or more times. This handles attributes or trailing text after the tag (e.g., <div>content).</li>
    <li>|: The OR operator separating the HTML logic from the ID logic.</li>
    <li>#([\w-]*): The second capturing group. It matches a hash symbol followed by zero or more word characters or hyphens, identifying ID selectors like #myId.</li>
</ul>

<p>Consequently, this regex successfully identifies strings such as <aa>, <div>content, #, and #identifier. The optimization matchResult = [null, target, null] specifically handles single-character tags (like <a>) that might otherwise fail the more complex regex validation or simply to provide a fast path. If the regex fails to match (e.g., plain text like "abc"), matchResult becomes null.</p>
</span></div></a>

Tags: javascript jquery DOM source-code-analysis regular-expressions

Posted on Wed, 19 Aug 2026 16:50:34 +0000 by bpopp