6

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');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1032531
  • 24,767
  • 68
  • 217
  • 387

4 Answers4

7

Try this using ternary operator:

.after(insertAfter ? $('<div />') : '')
antyrat
  • 27,479
  • 9
  • 75
  • 76
1

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);
Musa Hafalir
  • 1,752
  • 1
  • 15
  • 23
  • 1
    You doesn't return `this`, so after your function invoked you will not be able to work with this element. Only after accessing it again. – antyrat Dec 14 '12 at 14:30
  • 1
    And better is to wrap all into `this.each` before return so you can operate with all nodes with this selector, not only with first one. I mean `return this.each(function() {` – antyrat Dec 14 '12 at 14:32
  • 1
    Or maybe take this one step further, and extend a generic jQuery method which also takes the jQuery method (i.e. after() in this example)? – user1032531 Dec 14 '12 at 14:32
1

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

Robert Siemer
  • 32,405
  • 11
  • 84
  • 94
0

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

Community
  • 1
  • 1
  • 1
    I understand ternary operator and determining whether the variable is defined or not. My uncertainty was whether I could eliminate the after() method altogether based on a condition. – user1032531 Dec 14 '12 at 14:29