dom 4 easy mod 3.0

by ebaloSnositelXX

HTML

<body>
<div class="foo">
    <div class="bar-inside-foo">
        <div id="wow"></div>
        <div class="bar-inside-foo recursive-test-classFunc"></div>
    </div>
    <span class="bar-inside-foo"></span>
    <div class="bar-inside-foo"></div>
</div>
<div class="foo"></div>
</body>

JavaScript

function find(selector, context) {
    if (!context) {
        context = document.body;
    }
    /*
         if (context.querySelectorAll) {
         return context.querySelectorAll(selector);
         }
         */
    var checks = [
        {reg: /^\.([\w\-?]+)$/, func: getElementsByClassName},
        {reg: /^#([\w+-?]+)$/,  func: getElemByIdWithContext},
        {reg: /^(\w+)$/,        func: pipe(context.getElementsByTagName.bind(context), collectionToArray)}
    ];
    selector = selector.trim();
    var correctSelector = false;
    var array = [];
    for (var i = 0; i < checks.length; i++) {
        var match = selector.match(checks[i].reg);
        if (!match) {
            continue;
        }
        correctSelector = true;
        var result = checks[i].func(match[1], context);
        array = array.concat(result);
        break;
    }
    if (!correctSelector) {
        throw new Error("Неправильный селектор.");
    }
    return array;
}

function pipe(func1, func2) {
    return function() {
        var result = func1.apply(func1, arguments);
        return func2(result);
    }
}

function collectionToArray(collection) {
    return Array.prototype.slice.call(collection);
}

function getElementsByClassName(selector, context) {
    /*
        if (this.getElementsByClassName) {
            return this.getElementsByClassName(selector);
        }
        */
    return getElementsByProperty("className", selector, context);
}

function getElementsByProperty(property, selector, context) {
    if (typeof property != "string" ||
        typeof selector != "string") {
        throw new Error("Аргумент нe строка.");
    }
    var result = [];
    var elements = context.children;
    if (!elements) {
        return null;
    }
    var regex = new RegExp("(^|\\s+)" + selector + "($|\\s+)");
    for (var i = 0; i < elements.length; i++) {
        if (elements[i][property] === undefined) {
            throw new Error("У эл-та отсутствует св-во " + property);
       ...