Convert jQuery.get() to Vanilla JavaScript

on in AJAX and Fetching Data
Last modified on

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!

Related posts