17

Inside my jquery Append() I wan't to run an IF-statement to include an image on all my objects except on the first one.

Like:

var i = 0;

$('#divDetailsForSelectedInfo').append(
    '<div class="roundedAndBoxShade leftResultObject" id = "' + value.Query.Id + '">'+
    '<div class="leftResultObject_inner">' +
if (i > 0){
   <img src="/img.jpg"/>;
}
'<div>asdf</div>');

The code is generated by Json+Jquery and then it is all appended on a div in my index-file. As far as I've been able to tell through immence google-ing this can't be done, but I might be wrong?

If it is indeed "impossible", could the :first selector in Jquery be used in some cool way?

Solders
  • 391
  • 1
  • 4
  • 11

3 Answers3

42

A simpler solution:

var i = 0;
$('#somediv').append(
    'html before' + 
    (i > 0 ? '<img src="/img.jpg"/>': '') +
    'more html'
);
Kostia
  • 6,284
  • 1
  • 18
  • 15
7
var i = 0;
var str=''
if (i > 0){
  str =  '<img src="/img.jpg"/>;'
}
$('#divDetailsForSelectedInfo').append(
    '<div class="roundedAndBoxShade leftResultObject" id = "' + value.Query.Id + '">'+
    '<div class="leftResultObject_inner">' +str+'<div>asdf</div>');
Salil
  • 46,566
  • 21
  • 122
  • 156
2

The easiest way I can think of to do this:

$('#divDetailsForSelectedInfo').append(
    function(i) {
        return '<div class="roundedAndBoxShade leftResultObject" id = "' + value.Query.Id + '">' + '<div class="leftResultObject_inner">' + (i > 0 ? '<img src="/img.jpg"/>' : '');
    });

JS Fiddle proof-of-concept.

David Thomas
  • 249,100
  • 51
  • 377
  • 410