19

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?

4
  • 1
    Why don't you just .appendChild(templateString) and remove the 'test' references Commented Feb 21, 2017 at 16:16
  • Or just do const test = document.createElement('div'); test.innerHTML = prop.text; No string interpolation needed... Commented Feb 21, 2017 at 16:17
  • Are you sure that prop.text is allowed to contain arbitrary html? Commented Feb 27, 2017 at 22:58
  • 1
    related - stackoverflow.com/q/494143/104380 Commented Jun 12, 2018 at 21:20

2 Answers 2

23

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".

Sign up to request clarification or add additional context in comments.

Comments

16

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

1 Comment

A snippet to get the element: const domParse = (hmtl) => new DOMParser().parseFromString(html, "text/html").body.firstChild

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.