Skip to content

Instantly share code, notes, and snippets.

@cybardev
Created March 21, 2022 07:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cybardev/88c3e529779dcce3f70065e48cd23f10 to your computer and use it in GitHub Desktop.
Save cybardev/88c3e529779dcce3f70065e48cd23f10 to your computer and use it in GitHub Desktop.
JavaScript helper functions to replace JQuery for personal and academic projects.
/**
* Aliases to create DOM objects using $() like in JQuery
*
* @author Sheikh Saad Abdullah
* @param {String} selector selector for the element
* @returns DOM Object for specified element
*/
const $ = (selector) => {
return selector[0] === "#"
? document.querySelector(selector)
: document.querySelectorAll(selector);
};
/**
* Wrapper function around the fetch API to make GET requests
*
* @author Sheikh Saad Abdullah
* @param {String} endpoint address to send request to
* @returns response from the server
*/
$.get = (endpoint) => {
let response = null;
fetch(endpoint, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
})
.then((res) => {
response = res.json();
})
.catch((err) => {
console.log(err);
});
return response;
};
/**
* Wrapper function around the fetch API to make POST requests
*
* @author Sheikh Saad Abdullah
* @param {String} endpoint address to send request to
* @param {Object} data data to send to the server
* @returns response from the server
*/
$.post = (endpoint, data) => {
let response = null;
fetch(endpoint, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
.then((res) => {
response = res.json();
})
.catch((err) => {
console.log(err);
});
return response;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment