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
?
In ES6, we can now use template strings. I like to use these multiline strings when I'm creating HTML markup as a string. You can use backticks here, and use the object properties as variables. These look familiar because they're in the same format as I've been using in some of the previous posts.
Sanitising HTML with a Tagged Template Literal You can do that in a template literal tag using a library like html-parser2. We want to have two types of input into the placeholder, raw text strings which needs sanitising and safe HTML which is either authored by us or has been put through the sanitiser.
Backticks are an ES6 feature that allows you to create strings in JavaScript. Although backticks are mostly used for HTML or code embedding purposes, they also act similar to single and double quotes. Besides, using backticks makes it easier for string operations.
The createElement() method is used for creating elements within the DOM. It accepts two parameters, a tagName which is a string that defines the type of element to create, and an optional options object that can be used to modify how the element is created.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With