skip to Main Content

I am wanting to select the last 4 elements using nth-child. Is there a way of doing this?

function(data){
    var output;
    var html = "";
    $.each(data.items, function(i, item){
    videoTitle = item.snippet.title;
    videoId = item.snippet.resourceId.videoId;
    console.log(i);
    html += "<div id="video" class="col-xs-12 col-sm-6 link-js">n" +
                  "         <iframe width="100%" src="http://www.youtube.com/embed/"+videoId+""></iframe>n" +
        "    </div>"
});
$('#youtube-v3').append(html);
}

2

Answers


  1. Firstly you need to remove the id attribute from the HTML you create as you’re creating duplicates which is invalid. id have to be unique within the DOM. Change it to a class.

    Then you can what you require outside of your loop using slice(). It’s also possible to simplify the code and make it more performant by using map() to create the HTML from the data.items array and calling append() only once.

    function(data) {
      var html = data.items.map(item => `<div class="video col-xs-12 col-sm-6 link-js"><iframe width="100%" src="http://www.youtube.com/embed/${item.snippet.resourceId.videoId}"></iframe></div>`);
      $('#youtube-v3').append(html);
    
      var $lastVideos = $('.video').slice(-4);
      // do something with the last 4 videos here...
    }
    
    Login or Signup to reply.
  2. As you are already using a loop,compare the index in the loop with the length of the array and you can check if index >= 4.
    Using this, add your desired class only when index >= 4, which will be true only for elements after 4th one (i.e. 5th,6th,7th,8th element)

    PS: Remove the same id on HTML tags.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search