Can't run IIFE inside template

I am using an element <template>

, but the javascript code inside it does not run. I am using IIFE to get it working right away, but no luck.

<div id="content">
  initial text
</div>

<template>
  <script>
    (function(){
        document.querySelector('#content').innerHTML = 'new text';
    })();
  </script>
</template>
      

Run codeHide result


+3


source to share


1 answer


The content of the templates is not displayed in the DOM, so the script does not run.

from DOCS (first paragraph):

The HTML element is a mechanism for client-side hosting of content that should not be rendered on page load, but can subsequently be generated at runtime using JavaScript.



EDIT
Following your comment on how to run the code, there are several ways. just one grabs its content and throws it into DOM

:

<div id="content">
  initial text
</div>


<template>
  <script>
    (function(){
        document.querySelector('#content').innerHTML = 'new text';
    })();
  </script>
</template>

<script>
   var content = document.querySelector('template').content;
   document.body.appendChild(content,true);
</script>
      

Run codeHide result


+3


source







All Articles