user1032531
user1032531

Reputation: 26301

jQuery conditional chaining

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');

Upvotes: 6

Views: 2684

Answers (4)

Robert Siemer
Robert Siemer

Reputation: 34737

A couple of jQuery methods allow passing a function func. Often not clearly documented, but returning undefined from func is like a no-op, even in setters like .attr('src', func).

(In this setter example, func should return whatever you want 'src' set to otherwise.)

Upvotes: 1

There are numerous examples, here on stack overflow on how to check if a variable is defined.:

Then you can use break and continue to control the flow.

http://www.w3schools.com/js/js_break.asp

Upvotes: 0

Musa Hafalir
Musa Hafalir

Reputation: 1770

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);

Upvotes: 1

antyrat
antyrat

Reputation: 27765

Try this using ternary operator:

.after(insertAfter ? $('<div />') : '')

Upvotes: 7

Related Questions