Slayther Slayther - 1 year ago 44
CSS Question

Create HTML code that isn't parsed by browser (for reuse)

I have a snippet of HTML code that I want to reuse throughout my page.

<div class="gmail-message-container">
<span class="trim-text">
<span class="gmail-sender"> (Some Name)
<b><span class="trim-text gmail-title">Some title</span></b>
<span class="trim-text gmail-summary">Some summary text goes here</span>

How can I make the
serve as html element that isn't being shown and can be grabbed by JavaScript and appended to multiple places?

The element is assigned certain CSS rules that affect the element based on number of elements inside the container, hence I cannot just do
display: none;
, as it will count in the element I'm trying to copy.

Answer Source

a common pattern for such purposes is to use

<script type="text/template" id="template">
// your html goes here

text/template prevents browser from parsing the insides of <script> tag (you can use something different, it is only required not to use text/javascript to do so)

you can grab your template later by using document.getElementById('template').innerHTML