Elliott James
Elliott James

Reputation: 165

Change JQuery .append output using nth-child if statement

I'm listing 6 articles using .append(see below) and want to change which grid size they use depending on which iteration they are in the output. I have set this as var grid = 'x'. I want this to change depending on what child the article is of ul#news.

Using the code below, every article defaults to < li class="sm-12 m-3 cls" >

I believe the principles of what i'm doing to be correct, but something isn't working. Can anyone help?

Many thanks!

for (var i = 0; i < data.response.total; i++) {
    if ('ul#news li:nth-child(0)') {
        var grid = "sm-12";
    } else if ('ul#news li:nth-child(1)') {
        var grid = "sm-12 m-6";
    } else {
        var grid = "sm-12 m-3";
    };
    var thumbnail = data.response.results[i].blocks.main.bodyHtml;
    var title = data.response.results[i].webTitle;
    $('ul#news').append('<li class="' + grid + ' cls">' + thumbnail + '<h2>' + title + '</h2></li>');
};

Current Output

<ul id="events" >
  <li class="sm-12 m-3 cls"></li>
  <li class="sm-12 m-3 cls"></li>
  <li class="sm-12 m-3 cls"></li>
  <li class="sm-12 m-3 cls"></li>
  <li class="sm-12 m-3 cls"></li>
  <li class="sm-12 m-3 cls"></li>
</ul>

What I hope to achieve

<ul id="events" >
  <li class="sm-12 cls"></li>
  <li class="sm-12 m-6 cls"></li>
  <li class="sm-12 m-3 cls"></li>
  <li class="sm-12 m-3 cls"></li>
  <li class="sm-12 m-3 cls"></li>
  <li class="sm-12 m-3 cls"></li>
</ul>

Upvotes: 0

Views: 62

Answers (1)

T J
T J

Reputation: 43156

Your selectors in the if condition is missing the jQuery constructor $(), also you seems to be assuming that the element is already in the ul>, but it's not there yet, So you need to count what is already in it. So your code should be something like:

for (var i = 0; i < data.response.total; i++) {
  if ($('ul#news li').length == 0) { // currently empty, first element going to be inserted
    var grid = "sm-12";
  } else if ($('ul#news li').length == 1) { // second element going to be inserted
    var grid = "sm-12 m-6";
  } else {
    var grid = "sm-12 m-3";
  };
  var thumbnail = data.response.results[i].blocks.main.bodyHtml;
  var title = data.response.results[i].webTitle;
  $('ul#news').append('<li class="' + grid + ' cls">' + thumbnail + '<h2>' + title + '</h2></li>');
};

Upvotes: 1

Related Questions