Let's say I have the following jQuery code. It works great, but then I need to include the .after($('<div />')) only if var insertAfter equals true. Is there an elegant jQuery way of doing this?
$('#whatEver')
    .parent()
    .show()
    .width(123)
    .addClass('bebo')
    .before($('<div />'))
    .after($('<div />'))
    .parent()
    .addClass('bla');
                Try this using ternary operator:
.after(insertAfter ? $('<div />') : '')
                        You can extend jQuery library like this:
$(function () {
    $.fn.afterif = function (param, condition) {
        if (condition) {
            $(this).after(param);
        }
        return this;
    }
}(jQuery));
And use it like this:
var insertAfter = true;
$('#whatEver').afterif($('<div />'), insertAfter);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With