Reputation: 23120
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
?
Upvotes: 20
Views: 17479
Reputation: 23120
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
Upvotes: 16
Reputation: 350345
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".
Upvotes: 23