tickle/modules/utils/generateDomFromString.mjs

43 lines
1.1 KiB
JavaScript
Raw Permalink Normal View History

2023-05-09 02:00:53 +00:00
//@ts-check
/**
* Generates valid dom elements from a string
* @param {string} htmlString
*/
2023-05-13 15:26:48 +00:00
export const generateDomFromString = (htmlString) => {
htmlString = htmlString.trim();
const dom = new DOMParser().parseFromString('<template>'+ htmlString +'</template>','text/html')
const content = /** @type {HTMLTemplateElement} */(dom.head.firstElementChild).content
const fragment = document.createDocumentFragment();
fragment.append(content);
return fragment;
};
2023-05-09 02:00:53 +00:00
export default generateDomFromString;
2023-05-13 15:26:48 +00:00
/**
* @param {String} html representing a single element
* @return {Element|null}
*/
function htmlToElement(html) {
html = html.trim();
var template = document.createElement("template");
template.innerHTML = html;
if (template.content.childNodes.length) {
}
return /** @type {Element} */ (template.content.firstChild);
}
/**
* @param {String} html representing any number of sibling elements
* @return {NodeList}
*/
function htmlToElements(html) {
var template = document.createElement("template");
template.innerHTML = html;
return template.content.childNodes;
}