Question

Perhaps a strange question! I developer created a jquery/JSON function to load some products! He is building up the HTML in a way I don't know. I'm trying to add an if statement between the code but I can't get that to work.

Any suggestions?

 $.getJSON(url, function(json){
 $.each(json.products, function(index, product){
... some more code ....

  $('<div>').addClass('item-meta-container').append(
    $('<div>').addClass('ratings').append(
      $('<div>').addClass('ratings-result').css('width',+productScore+'px')
      )
     ).append(

// in here I want an if statement //

   ).appendTo(object)

This is the only way to do it. So I want to add an if statement like

       if(mode == 'list'){
         $('<div>').addClass('product-description').html(product.description).appendTo(productObject);
        }

How do you do that?

Was it helpful?

Solution

As you can read here, append() expects Type: htmlString or Element or Array or jQuery

I think you should build your content (empty or div) and then append it like this:

//--- check if mode == 'list' on the outside
var myContent = (mode == 'list') ? $('<div>').addClass('product-description').html(product.description).appendTo(productObject) : "";

$('<div>').addClass('item-meta-container').append(
    $('<div>').addClass('ratings').append(
        $('<div>').addClass('ratings-result').css('width',+productScore+'px')
    )
).append(myContent) //--- Here's your content!
 .appendTo(object);

Have a look HERE for a simplified example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top