xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js parser HTML template string to DOM element All In One

js parser HTML template string to DOM element All In One

DOMParser 🚀

/*
function element(template, mimeType) {
  return (new DOMParser).parseFromString(template, mimeType).body.firstElementChild;
}
*/

function element(template, mimeType) {
  return new DOMParser().parseFromString(template, mimeType).body.firstElementChild;
}

/* test */

var template = `
<div class="repository">
 <div var="name"></div>
 <p var="text"></p>
 <img var="image"/>
</div>
`;

var test = element(template, "text/html");
console.log(test);

https://gist.github.com/xgqfrms/c233223a3012bb52148045d78a6ec2f3

https://developer.mozilla.org/en-US/docs/Web/API/DOMParser

parseFromString(string, mimeType)

https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString

document.body.innerHTML


const markup = `
  <div>html template string</div>
`;

document.body.innerHTML = markup;

function htmlToElem(html) {
  let temp = document.createElement('template');
  html = html.trim(); 
   // Never return a space text node as a result
  temp.innerHTML = html;
  return temp.content.firstChild;
}

let td = htmlToElem('<td>foo</td>'),
   div = htmlToElem('<div><span>nested</span> <span>stuff</span></div>');
alert(td);
alert(div);

function htmlToElems(html) {
  let temp = document.createElement('template');
  temp.innerHTML = html;
  return temp.content.childNodes;
}
let rows = htmlToElems('<tr><td>foo</td></tr><tr><td>bar</td></tr>');
alert(rows);

https://www.w3docs.com/snippets/javascript/how-to-create-a-new-dom-element-from-html-string.html

document.body.insertAdjacentHTML


const templateString = `
  <div>html template string</div>
`;

// 创建 DOM 模版
if(!document.querySelector(`#wcui-button-template`)) {
  document.body.insertAdjacentHTML(`beforeend`, templateString);
}
const template = document.querySelector(`#wcui-button-template`);

https://www.npmjs.com/package/@xgqfrms/wcui

refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-07-06 16:50  xgqfrms  阅读(49)  评论(1编辑  收藏  举报