forked from HackYourFuture/JavaScript3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtil.js
More file actions
35 lines (33 loc) · 918 Bytes
/
Util.js
File metadata and controls
35 lines (33 loc) · 918 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
'use strict';
// eslint-disable-next-line no-unused-vars
class Util {
static createAndAppend(name, parent, options = {}) {
const elem = document.createElement(name);
parent.appendChild(elem);
Object.keys(options).forEach((key) => {
const value = options[key];
if (key === 'text') {
elem.innerText = value;
} else {
elem.setAttribute(key, value);
}
});
return elem;
}
static fetchJSON(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = () => {
if (xhr.status < 400) {
resolve(xhr.response);
} else {
reject(new Error(`Network error: ${xhr.status} - ${xhr.statusText}`));
}
};
xhr.onerror = () => reject(new Error('Network request failed'));
xhr.send();
});
}
}