Index of object and play next with youtube api

I got a suggestion to get player.current_video by the closest li index, so I made an update to my data-video img tag.

<li class = liItem>
    <img data-video = "{{videoid}}" src = "bilder/play.png" alt = "play" class = "knapp" width = "40" height = "40">
</li>

Then I changed the index on my click function in my edited example:

$('#searchBar').on('click', '[data-video]', function(){
player.current_video = $(this).closest('li').index();
playVideo();
});

With this new fuction I was able to chose and play the next song! Shoutout to @cale_b for providing me with the .closest('li') suggestion.


Here is a working PEN (click to RUN)

The solution is based on a global currentSongIndex index, without facilitating next()

var currentSongIndex = null;

$(".knapp").click(function () {
    var index =  $(this).attr('data-video');
    playVideo(index);
});

function playVideo(index) {
    console.log("Playing song INDEX: " + index);
    currentSongIndex = index;
    playNext();
} 

function playNext() {
    currentSongIndex++;
    let nextSongIndex = $('img[data-video="' + currentSongIndex + '"]').attr('data-video');
    console.log("Next song INDEX: " + nextSongIndex);
    if(typeof nextSongIndex != "undefined") {
        playVideo(nextSongIndex);
    } else {
        console.log('end of list... you can play from index 1 or whatever....');
    }
}