Vadim P.
Vadim P.

Reputation: 2333

Strange behavior when applying Array.prototype.slice method to result of querySelectorAll

I'am trying to use jQuery's Sizzle selector engine as a custom Selenium locate API, as in this article: http://johnjianfang.blogspot.com/2009/04/how-to-use-jquery-to-create-custom.html

Unfortunatly, when I use selenium.click('jquery=a.mylink'), nothing happens.

selenium.click('css=a.mylink') works perfectly.

I did a little research, and found that problem is in how jQuery converts the result of the querySelectorAll API. Here is the snippet from jQuery 1.4.2:

Sizzle = function(query, context, extra, seed){
    context = context || document;

    // Only use querySelectorAll on non-XML documents
    // (ID selectors don't work in non-HTML documents)
    if ( !seed && context.nodeType === 9 && !isXML(context) ) {
        try {
            return makeArray( context.querySelectorAll(query), extra );
        } catch(e){}
    }

    return oldSizzle(query, context, extra, seed);
};


var makeArray = function(array, results) {
    array = Array.prototype.slice.call( array, 0 );

    if ( results ) {
        results.push.apply( results, array );
        return results;
    }

    return array;
};

When I change makeArray like this:

var makeArray = function(arrayLikeObject, results) {

    var array = new Array(arrayLikeObject.length);
    for (var i = 0, n = arrayLikeObject.length; i < n; i++) {
        array[i] = arrayLikeObject[i];
    }

    if ( results ) {
        results.push.apply( results, array );
        return results;
    }

    return array;
};

It solves this strange problem.

Any ideas why this fix works??!

Upvotes: 3

Views: 390

Answers (1)

Paul Sweatte
Paul Sweatte

Reputation: 24627

The browser may not be able to convert a nodeList to an array using built-in methods. Your fallback is almost exactly like the one included further down in the jQuery 1.4.2 source:

// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
    Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;

// Provide a fallback method if it does not work
} catch(e){
    makeArray = function(array, results) {
        var ret = results || [];

        if ( toString.call(array) === "[object Array]" ) {
            Array.prototype.push.apply( ret, array );
        } else {
            if ( typeof array.length === "number" ) {
                for ( var i = 0, l = array.length; i < l; i++ ) {
                    ret.push( array[i] );
                }
            } else {
                for ( var i = 0; array[i]; i++ ) {
                    ret.push( array[i] );
                }
            }
        }

        return ret;
    };
}

Upvotes: 1

Related Questions