JQuery conditional chain

Let's say I have the following jQuery code. It works fine, but then I need to include .after($('<div />')) only if var insertAfter is true. Is there an elegant jQuery way to do this?

 $('#whatEver') .parent() .show() .width(123) .addClass('bebo') .before($('<div />')) .after($('<div />')) .parent() .addClass('bla'); 
+4
source share
3 answers

Try using the ternary operator:

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

You can extend the jQuery library as follows:

 $(function () { $.fn.afterif = function (param, condition) { if (condition) { $(this).after(param); } return this; } }(jQuery)); 

And use it as follows:

 var insertAfter = true; $('#whatEver').afterif($('<div />'), insertAfter); 
+1
source

There are many examples that describe stack overflows 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

0
source

All Articles