minsky-kit
Version:
Kit of components for MINSKY web agency
25 lines (21 loc) • 765 B
JavaScript
// imports
import { createLogger } from './createLogger';
const log = createLogger('Dom - util');
// tries to convert a string to a dom element by adding the given string to the dom and extracting it through a generated parent.
export function strToDom (tpl) {
if (typeof tpl === 'string') {
const parser = new DOMParser();
const $html = parser.parseFromString(tpl, 'text/html');
const errorNode = $html.querySelector('parsererror');
if (errorNode) {
// parsing failed
log('error', 'Parsing failed', errorNode, { $html });
}
else {
// parsing succeeded
tpl = $html.body.children;
if (tpl.length === 1) tpl = tpl[0];
}
}
return tpl;
}