I am adding some conditional logic to check for elements in an array and if they exist, adding classes using JS-generated mark-up to do so. Is there a way to add conditional logic in between two strings (which are outputted as markup from JS) to reduce some of this redundant conditional logic?
for (var i=0; i<data.length; i++) {
var gallery = data[i];
if (typeof gallery.showcase !== "undefined") {
if (typeof gallery.video !== "undefined") {
$(
"<li class='video " + (typeof gallery.video !== "undefined" ? "test ") + gallery.showcase + "'>" +
"<a href='" + gallery.link + "'></a>" +
"</li>").appendTo("#gallery ul");
}
else {
$(
"<li class='image " + gallery.showcase + "'>" +
"<a href='" + gallery.link + "'>" +
"<img src=" + gallery.image + " alt='" + gallery.title + "'>" +
"</a>"
+ "</li>").appendTo("#gallery ul");
}
}
else {
if (typeof gallery.video !== "undefined") {
$(
"<li class='video'>" +
"<a href='" + gallery.link + "'></a>" +
"</li>").appendTo("#gallery ul");
}
else {
$(
"<li class='image'>" +
"<a href='" + gallery.link + "'>" +
"<img src=" + gallery.image + " alt='" + gallery.title + "'>" +
"</a>"
+ "</li>").appendTo("#gallery ul");
}
}
}
What I am hoping for is to add classes to the JS-generated markup doing conditional checks in a much more cleaner manner. Thoughts?
You have a lot of repetition – you can achieve what you need by identifying common strings or elements and refactoring the code somewhat.
I’m not 100% sure this is correct (since to be honest the original code is somewhat hard to parse) but it should demonstrate approximately how you would solve this.