HTML String
by Raul Bojalil
HTML
<div id="app">
</div>
JavaScript
function getHtml(url) {
return new Promise((resolve, reject) => {
var request = new XMLHttpRequest();
request.open('POST', url, true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var resp = this.response;
resolve(resp);
} else {
reject();
}
};
request.onerror = function() {
reject();
};
request.send();
});
}
getHtml("/echo/html/").then((e) => {
console.log(e);
});
function appendHtml(element, htmlStr) {
element.insertAdjacentHTML('beforeend', htmlStr);
var ids = {};
var items = document.getElementById("app").querySelectorAll("[id]");
for(var i=0; i < items.length; i++) {
ids[items[i].id] = items[i];
}
return ids;
}
var html = `
<div id="one">
</div>
<div id="two">
</div>`;
var html2 = `
<button id="three">Three
</button>
<table id="four">
<thead>
<tr><th>One</th><th>Two</th></tr>
</thead>
<tbody id="fourbody">
</tbody>
</table>
`;
var container = document.getElementById('app');
var view = appendHtml(container, html);
view.one.innerHTML = "One";
view.two.innerHTML = "Two";
var view2 = appendHtml(container, html2);
view2.three.addEventListener("click", () => {
alert("Three");
});
appendHtml(view2.fourbody, '<tr><td>1</td><td>2</td></tr>')