14

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
  • 19,976
  • 26
  • 76
  • 109

2 Answers2

20

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
  • 263,463
  • 30
  • 215
  • 251
12

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
  • 103,437
  • 51
  • 275
  • 359
chrisjlee
  • 19,976
  • 26
  • 76
  • 109