jQuery.fn.or()

by rwaldron

HTML

<p>A paragraph</p>
<p class="another">
Another paragraph
</p>
<p class="devious">
devious paragraph 1
</p>
<p class="devious">
devious paragraph 2
</p>

JavaScript

function equal( actual, expected, message ) {
    console.log(
        ( actual === expected && "PASS" ) || "FAIL", 
        message + ", Expected: " + expected + "; Actual: " + actual 
    );     
}

// PLUGIN STARTS HERE
(function( jQuery ) {
    
    jQuery.fn.or = function( selector ) {
        return this.length ? this : jQuery( selector );
    };
    
})( jQuery );
// PLUGIN ENDS HERE

// usage:
// jQuery("p.nonexistant").or("p.another")




equal(
    jQuery("p").length, 4, "Find 3 [p] elements"
);
equal(
    jQuery("p.another").length, 1, "Find 1 [p.another] element"
);
equal(
    jQuery("p.nonexistant").length, 0, "Find 0 [p.nonexistant] elements"
);

// Implementation tests:

equal(
    jQuery("p.nonexistant").or("p.another").length, 1, "Find 1 [p.another] element when 0 [p.nonexistant] elements could be found"
);
equal(
    jQuery("p.another").or("p.devious").length, 1, "Find 1 [p.another] element, .or() does not change the selection"
);