Reputation: 26301
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
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
Reputation: 2916
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
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
Reputation: 27765
Try this using ternary operator:
.after(insertAfter ? $('<div />') : '')
Upvotes: 7