Created
March 21, 2022 07:12
-
-
Save cybardev/88c3e529779dcce3f70065e48cd23f10 to your computer and use it in GitHub Desktop.
JavaScript helper functions to replace JQuery for personal and academic projects.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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