template literal to DOM

Basic example of using a tagged template literals with the DOM

by Julien Etienne

HTML

<!-- 
  A basic example of how to use tagged template literals with the DOM
  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
-->

JavaScript

/*
 You don't need to use a closure here, it's just my preference. 
 1. Create the template element,this also allows you to use table elements etc without problems
 2. Insert the markup inside the template (Does not render does not execute does not duplicate when you append)
 3. Get the first element, node, or whatever nodeType within the template
*/
const createMarkupPartial = (nodeMethod) => {
  const template = document.createElement('template');
  return string => {
  console.log('string', string)
    template.insertAdjacentHTML('afterbegin', string);
    return template[nodeMethod];
  }
}

/* 
	Because this is a basic example we are only considering
  elements. You can easily extend this to other nodetypes.
  Ideally you only need to do this once.
*/
const html = createMarkupPartial('firstElementChild');

/* Create HTML or whatever */
/* Yes there are sytnax highlighters */
const greeting = html `
<div>
  <h1>Stop using JSX!</h1>
  <table><tr>I aM a bAd TAbLe</tr></table>
  <svg height="210" width="400">
  	<path d="M50 0 L50 50 L100 50 Z" fill="lime"/>
	</svg>
</div>`;

// Render
document.body.append(greeting);