SoFunction
Updated on 2025-04-13

YUI code reading diary - Part.1

Let's first go around the head if...else (actually, it's the definition of two functions toCamel and getStyle) - This is why the browser implementation is not unified, so you can talk about these codes back.

Let’s take a look at what treasures are in the category. At present, the idea has gradually split. I saw a function and said a function.

// Basically, it can be considered a replica of
get: function(el) {
// If it is already HTMLElement, then return directly
    if (el && ( || )) {
        return el;
    }

// If it is a string, then return the Element with this ID
    if ((el) || !el) {
        return (el);
    }

// It looks like an array, looping to call itself, obtaining Element
    if ( !== undefined) {
        var c = [];
        for (var i = 0, len = ; i < len; ++i) {
            c[] = (el[i]);
        }

        return c;
    }

    return el;
}, This code is very exquisitely written. To be honest, if you don't think about it, you may be written as

for (var i = 0, len = ; i < len; ++i) {
    c[] = (el[i]);
}Although it can work normally, the previous judgment has lost its meaning.

Continue to take a quick look, now take a look at the internal mechanism of getElementsByClassName. For detailed calls to getElementsByClassName, please refer to the YUI document.

getElementsByClassName: function(className, tag, root, apply) {
// Get the tag tag, default to all ("*")
    tag = tag || '*';
// Specify the node name
    root = (root) ? (root) : null || document; 
    if (!root) {
        return [];
    }

// Initialize node information
    var nodes = [],
        elements = (tag),
        re = getClassRegEx(className);

// Filter out nodes that do not comply with the rules
    for (var i = 0, len = ; i < len; ++i) {
        if ( (elements[i].className) ) {
// You must be wondering why you use it instead of using it
// Think carefully :^)
            nodes[] = elements[i];
// Execute the callback function
            if (apply) {
                (elements[i], elements[i]);
            }
        }
    }

    return nodes;
}, Textbook-style DOM node acquisition and filtering, initialization data and operation data appear very rigorous and formal. The YUI code gives me a bit of a "secure". Similarly, let’s getElementsBy function, the corresponding code is as follows

getElementsBy: function(method, tag, root, apply) {
// Same as the above function,
    tag = tag || '*';
    root = (root) ? (root) : null || document; 

    if (!root) {
        return [];
    }

    var nodes = [],
        elements = (tag);

    for (var i = 0, len = ; i < len; ++i) {
// Judge the properties of the node based on the return value of the custom function
        if ( method(elements[i]) ) {
            nodes[] = elements[i];
            if (apply) {
                apply(elements[i]);
            }
        }
    }

    return nodes;
}, OK, let's be here today.