by tomp · 2y ago · 0 comments
const myDiv = div(
{id: 'container', className: 'my-class'},
h1('Hello World'),
p('This is a dynamically generated paragraph.')
);
document.body.appendChild(myDiv);
That's completely unnecessary these days with template strings. It's gonna be much faster as well to use browser's native parsing. const div = document.createElement('div');
let text = 'This is a dynamically generated paragraph';
div.innerHTML = `
<div id="container" class="my-class">
<h1>Hello world</h1>
<p>${text}</p>
</div>
`;
document.body.append(...div.children);
Keep it simple!Here's a way to do that with a tagged template function (named it `htmlFragment` to make it super clear what it's for):
// a couple of functions to help
const sanitizeHTML = (unsafeStr) => {
const div = document.createElement('div');
div.textContent = unsafeStr;
return div.innerHTML;
};
const htmlFragment = (fragments, ...variables) => {
const result = variables.map((variable, i) => fragments[i] + sanitizeHTML(variable));
result.push(fragments[fragments.length-1]);
return result.join('');
};
// updated your code here
const div = document.createElement('div');
let text = 'This is a dynamically generated paragraph';
div.innerHTML = htmlFragment`
<div id="container" class="my-class">
<h1>Hello world</h1>
<p>${text}</p>
</div>
`;
document.body.append(...div.children);
Unfortunately, to my knowledge there isn't yet a close-to-the-metal solution for templating and data binding in HTML/JS, although several proposals are currently being discussed.I'm hoping for this one:
const div = document.createElement('div');
const text = 'This is a dynamically generated paragraph';
div.insertAdjacentHTML("beforeend", `<div id="container" class="my-class">
<h1>Hello world</h1>
<p>${text}</p>
</div>`);
document.body.append(...div.children);
Edit, figured I'd add the docs: https://developer.mozilla.org/en-US/docs/Web/API/Element/ins...From the MDN page:
> When inserting HTML into a page by using insertAdjacentHTML(), be careful not to use user input that hasn't been escaped.
``` const myButton = button({ onclick: e => console.log(e), textContent: "Click me" }) ```