Convert es6 template string to html element using vanilla javascript

Is there a way to use plain old vanilla javascript (sans frameworks) to convert an html template string to an HTML element?

Here is what I have things I 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 uses innerHTML and adds an extra wrapped div. Is there any way to do this without additional div ?

+5
source share
2 answers

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 this string variable templateString, since there is no such thing as a variable that is a template string. Pattern strings are literal, but when evaluated, they are simple strings. There is nothing in the variable that has the magic templateness trace.

+9
source

I just discovered DomParser . And this is 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

+3
source

Source: https://habr.com/ru/post/1264528/


All Articles