ES6 (vanilla Javascript) replacements for jQuery

In jQuery one hase a lot of helpful methods. This is a list of vanilla Javascript way's to do the same without jQuery.

Loading Page HTML Fragments

jQuery

In jQuery one can use the load function to load a HTML fraction via Ajax.

$( "#result" ).load( "ajax/test.html #container" );

ES6

In plain JavaScript this could be done as follow.

function selectFragment(selector, html) {
    let df = document.createDocumentFragment();
    let tmpDiv = document.createElement('div');
    tmpDiv.innerHTML = html;
    df.appendChild(tmpDiv);
    return df.querySelector(selector);
}

const url = "ajax/test.html";
const response = await fetch(url, { method: "GET" });
const responseHtml = await response.text();
const contentHtml = selectFragment("#container", responseHtml);
let target = document.querySelector("#result");
target.innerHTML = contentHtml.innerHTML;

Document Ready

jQuery

$(document).ready(function() {
    console.log("DOM fully loaded and parsed");
});

ES6

document.addEventListener("DOMContentLoaded", (event) => {
    console.log("DOM fully loaded and parsed");
});
By @MrTango in
Tags :