jquery

why $(window).is(window) returns false


Anyone knows why:

$(window).is(window)

returns false

I (and all AIs) thought should be true, at least if you use a non window element it returns true.


Solution

  • This may be a bug in jQuery. .is(), .filter() and .not() all call an internal function winnow():

    function winnow( elements, qualifier, not ) {
        if ( isFunction( qualifier ) ) {
            return jQuery.grep( elements, function( elem, i ) {
                return !!qualifier.call( elem, i, elem ) !== not;
            } );
        }
    
        // Single element
        if ( qualifier.nodeType ) {
            return jQuery.grep( elements, function( elem ) {
                return ( elem === qualifier ) !== not;
            } );
        }
    
        // Arraylike of elements (jQuery, arguments, Array)
        if ( typeof qualifier !== "string" ) {
            return jQuery.grep( elements, function( elem ) {
                return ( indexOf.call( qualifier, elem ) > -1 ) !== not;
            } );
        }
    
        // Filtered directly for both simple and complex selectors
        return jQuery.filter( qualifier, elements, not );
    }
    

    To tell if the argument is a single element, it checks if qualifier.nodeType is truthy. But window.nodeType is undefined, so it falls through to the code that expects the argument to be a string selector or an array-like collection of elements (jQuery objects are array-like).

    Thus, if you wrap the argument in an array it works as expected:

    console.log($(window).is([window]))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>