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

Unlimited Automated Page Speed Monitoring & Tracking. Completely free.
Use SpeedFactor to track your website. It’s simple, reliable, and best of all, it’s free forever.
See how real people experience the speed of your website. Then find (and fix) your web performance problems.
Get Started

Related Articles


Privacy Policy