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
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 usingmap()
to create the HTML from thedata.items
array and callingappend()
only once.As you are already using a loop,
compare the index in the loop with the length of the array
and you can check ifindex >= 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.