Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a es6 template string to html element using vanilla javascript

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?

like image 403
chrisjlee Avatar asked Feb 21 '17 16:02

chrisjlee


People also ask

Can you use template strings in HTML?

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.

How do you write template literals in HTML?

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.

Can I use backticks JavaScript?

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.

How do you create a string element in HTML?

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.


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

like image 82
trincot Avatar answered Sep 18 '22 19:09

trincot