jQuery Conditional Chains

Playing with jQuery chain to make parts of it conditional. Have fun, but don't use it for real!

HTML

<p id="test1a">Test</p>

<p id="test1b">Test</p>

<ul id="test2a">
    <li id="ID">1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>

<ul id="test2b">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>

JavaScript

/*
 * Please note that it's in most cases useless and quite a bad practice!
 *
 * So have fun with it, but don't use it for real coding:
 * standard if/else statement will do this work in much better way!
 */

jQuery.fn.extend({
    when: function (condition) {
        var ret = this.pushStack("", "when", "");
        ret.otherwiseObject = this.pushStack("", "otherwise", "");
        
        if (jQuery.isFunction( condition )) {
            condition = condition.call(this);
        }
        jQuery.merge(condition ? ret : ret.otherwiseObject, this);
    
        return ret;
    },
    
    otherwise: function () {
        return this.otherwiseObject || jQuery();
    }
});



// TESTS

$("#test1a")
    .css("color", "red")
    .when(true)
        .css("color", "green")
        .append(" (when)")
    .otherwise()
        .css("color", "blue")
        .append(" (otherwise)")
    .end()
    .css("textDecoration", "underline");

$("#test1b")
    .css("color", "red")
    .when(false)
        .css("color", "green")
        .append(" (when)")
    .otherwise()
        .css("color", "blue")
        .append(" (otherwise)")
    .end()
    .css("textDecoration", "underline");

$('#ID').attr('rel', 'https://www.google.co.in/')
$("#test2a")
    .when( function(){ return this.children().length > 4 } )
        .css("color", "green")
    .otherwise()
        .css("color", "red");

$("#test2b")
    .when( function(){ return this.children().length > 4 } )
        .css("color", "green")
    .otherwise()
        .css("color", "red");