Convert jQuery.get() to Vanilla JavaScript

In the latest iteration of my YouTube Playlist Player plugin, I decided to remove all jQuery dependencies. I replaced the following jQuery each() loop with its JavaScript equivalent.

I have replaced:

jQuery.get("https://www.googleapis.com/youtube/v3/videos?part=snippet&fields=items(id,snippet)&id=" + videoId + "&key=" + ytApiKey, function (data) {
    var videoId = jQuery('.yt-api-container').data('vdid'),
        videoArray = videoId.split(',');

    jQuery.each(videoArray, function (index, value) {
        var videoElement = '<div class="yt-api-video-item yt-' + data.items[index].id + '" data-id="' + data.items[index].id + '"><div class="yt-api-video-thumb"><img src="' + data.items[index].snippet.thumbnails.high.url + '" alt="' + data.items[index].snippet.title + '"></div><div class="yt-api-video-description">' + data.items[index].snippet.title + '</div></div>';

        jQuery('.yt-api-video-list').append(videoElement);
    });
});

with:

var ytApiKey = document.querySelector('.yt-api-container').dataset.apikey,
    videoId = document.querySelector('.yt-api-container').dataset.vdid,
    httpRequest = new XMLHttpRequest();

httpRequest.open('GET', "https://www.googleapis.com/youtube/v3/videos?part=snippet&fields=items(id,snippet)&id=" + videoId + "&key=" + ytApiKey, true);
httpRequest.onreadystatechange = function (data) {
    if (httpRequest.readyState === 4) {
        data = JSON.parse(httpRequest.responseText);

        var videoId = videoId = document.querySelector('.yt-api-container').dataset.vdid,
            videoArray = videoId.split(','),
            videoElement;

        videoArray.forEach(function (item, index) {
            videoElement = '<div class="yt-api-video-item yt-' + data.items[index].id + '" data-id="' + data.items[index].id + '"><div class="yt-api-video-thumb"><img src="' + data.items[index].snippet.thumbnails.high.url + '" alt="' + data.items[index].snippet.title + '"></div><div class="yt-api-video-description">' + data.items[index].snippet.title + '</div></div>';

            document.querySelector('.yt-api-video-list').innerHTML += videoElement;
        });
    }
};
httpRequest.send();

Enjoy!

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.

πŸ‘‹ Added by Ciprian on Wednesday, July 4, 2018 in Blog, JavaScript. Last modified on Wednesday, July 4, 2018.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Privacy Policy