Jim22150 Jim22150 - 2 months ago 14
Javascript Question

Conditional Chain jQuery

Syntax question; is it possible to do the following:

var home_page_feed;
var videos = $get_utoob_videos;
for each(video in videos) {

...but in a single ternary operation, like this:

for each(video in videos)
$(home_page_feed) .CHAIN.
video.special_interests ?
// true - chain this
.prepend(video.thumbnail) :
// false - chain this instead

I put .CHAIN. as a placeholder. Is there a jQuery function that would chain to a incomplete statement by means of ternary operation assignment? I enjoy using ternary for statements and operations because of it's simplicity, so any help would be appreciated.

Here is a dirty solution I've come up with in the past for PHP scripts where trying to do the same thing. I don't like it because it relies heavily successful page load runtime.

for each($video in $videos) {
$chain =
$video.special_interests ?
".phpPrepend(video.thumbnail)" :
$home_page_feed . $chain;

Thanks to @Barmar, who suggested the use of the eval() function, I was able to wrap it around the ternary operation.

$.each(videos, function(i, video) {
eval ("$(home_page_feed)" +
video.special_interest ?
".prepend(video.thumbnail)" :


You can put the ternary in the argument to .append()

$.each(videos, function(i, video) {
    $(home_page_feed).append(video.special_interests ? video.thumbnail : video.censornail);

Or you can put it in the index:

$.each(videos, function(i, video) {
    $(home_page_feed).append(video[video.special_interests ? "thumbnail" : "censornail"]);

Note the quotes in the last version.

You could do your code using eval()

$.each(videos, function(i, video) {
    var chain = video.special_interest ? 
        ".prepend(video.thumbnail)" :
    eval ("$(home_page_feed)" + chain);