17

Is there a method to use plain old vanilla javascript (sans frameworks) to convert a html template string into a Html element?

Here's what i've things that i've tried:

function renderBody(selector = body, template) {
    const prop.text = 'foobar';
    const templateString = `<div id='test'>${prop.text}</div>`
    const test = document.createElement('div');
    test.innerHTML = templateString;
    document.querySelector(selector).appendChild(test);
}

This implementation works but it uses innerHTML and adds an extra wrapped div. There a way to do that without the extra div?

chrisjlee
  • 21,691
  • 27
  • 82
  • 112

2 Answers2

21

You can use insertAdjacentHTML:

function renderBody(selector = 'body', template) {
    const prop = { text: 'foobar' };
    const html = `<div id='test'>${prop.text}</div>`;
    document.querySelector(selector).insertAdjacentHTML('beforeend', html);
}

renderBody();
div { border: 1px solid }
<h1>test</h1>

I would not call that string variable templateString as there is no such thing as a variable that is a template string. Template strings are a literal notation, but when evaluated, they are plain strings. There is nothing in the variable that has some magical trace of "templateness".

trincot
  • 317,000
  • 35
  • 244
  • 286
15

I just discovered DomParser. And that's what i was looking for:

let doc = new DOMParser().parseFromString('<div><b>Hello!</b></div>', 'text/html');

Credit: https://davidwalsh.name/convert-html-stings-dom-nodes

vsync
  • 118,978
  • 58
  • 307
  • 400
chrisjlee
  • 21,691
  • 27
  • 82
  • 112
  • 1
    A snippet to get the element: `const domParse = (hmtl) => new DOMParser().parseFromString(html, "text/html").body.firstChild` – Tommy Aug 29 '22 at 19:42