Skip to content

Instantly share code, notes, and snippets.

@xgqfrms
Forked from dfkaye/element.js
Created July 6, 2022 08:47
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 xgqfrms/c233223a3012bb52148045d78a6ec2f3 to your computer and use it in GitHub Desktop.
Save xgqfrms/c233223a3012bb52148045d78a6ec2f3 to your computer and use it in GitHub Desktop.
Create a DOM element from template string using DOMParser
// 1 April 2020
// variant on jsx in vanilla.js
// see https://gist.github.com/dfkaye/f3229e5ace79b6873022987f160c7b61
// takes a template string and mimeType
// returns dom element from the template string
// TODO (maybe) - add UI map capability - i.e. UI = { name: <node with var=name> }
function element(template, mimeType) {
return (new DOMParser)
.parseFromString(template, mimeType)
.body
.firstElementChild;
}
/* test it out */
var t = `
<div class="repository">
<div var="name"></div>
<p var="text"></p>
<img var="image"/>
</div>
`;
var test = element(t, "text/html")
console.log(test);
/*
<div class="repository">
<div var="name"></div>
<p var="text"></p>
<img var="image"/>
</div>
*/
// Helpers based on MDN table at bottom...
function toHtml(template) {
return element(template, "text/html")
}
function toXml(template) {
return element(template, "text/xml")
}
function toSvg(template) {
return element(template, "image/svg+xml")
}
/*
[https://developer.mozilla.org/en-US/docs/Web/API/DOMParser]
| mimeType | doc.constructor |
| --- | --- |
| text/html | Document |
| text/xml| XMLDocument |
| application/xml | XMLDocument |
| application/xhtml+xml | XMLDocument |
| image/svg+xml | XMLDocument |
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment