Nicola Bertelloni
Nicola Bertelloni

Reputation: 333

html import .appendChild method

I need to import some html files in my page, everything is working fine, BUT the script I'm using append the content after the <section> and i need it in the same spot where I have inserted the JS

  <script>
    var getImport  = document.querySelector('#wl-mock-160-s1-import');
    var getContent = getImport.import.querySelector('#wl-mock-160-s1');
      document.body.appendChild(document.importNode(getContent, true));
  </script>

In case you need it, the imported html look like this

<div id="wl-mock-190-s2">
  <div class="wl-mock-190-s2-top-wrap">

    <h2 class="wl-mock-190-s2-ent">Parlamento Europeo</h2>

    <div class="wl-mock-190-s2-img-wrap">
      <img src="../../assets/img/jpg/img-8.jpg" alt="">
      <img src="../../assets/img/png/play.png" alt="" class="wl-mock-190-s2-play">
    </div>
  </div>
  <h2 class="wl-mock-190-s2-title">Produciamo nuove contaminazioni. <br>
    Fukushima, Nagasaki e Mururoa.</h2>

  <p class="wl-mock-190-s2-p">Fukushima, Nagasaki e Mururoa. E vaccini ed olocausti e paradossi. Etilone, nefedrone e così via.</p>

    <button>Continua a leggere</button>

</div>

I tried using .html() method but it fails.

Upvotes: 1

Views: 508

Answers (1)

tomalec
tomalec

Reputation: 900

Your own vanilla way

You need to use currentScript

<script>
  var getImport  = document.querySelector('#wl-mock-160-s1-import');
  var getContent = getImport.import.querySelector('#wl-mock-160-s1');
  // Get the pollyfiled/native current script
  var currentScript = var ownerDocument = document._currentScript || document.currentScript;
  // Put is before your element
  currentScript.parentNode.insertBefore(document.importNode(getContent, true), currentScript);
</script>

but you do not have to bother about it by yourselfe, as ...

There is a custom element for that

Try <imported-template> - custom element that imports HTML content from external file. It uses HTML Import to load the file, then stamps the content of <template> to current place in HTML tree:

main.html

<link rel="import" href="bower_components/imported-template/imported-template.html">
<h1>Your main document that will import something else </h1>
<!-- The imported HTML will come here -->
<template is="imported-template" content="/path/to/external_file.html"></template>

where you can use anything HTML document allows in your

external_file.html

<!-- Preload some dependencies etc.-->
<link rel="import" href="awesome-component.html">
<script src="init/some/stuff.js"></script>
<template>
  <!-- This will get stamped -->
  <h1>Hello World</h1>
  <awesome-component></awesome-component>
  <script>doMagicPerStampedContent();</script>
</template>

Upvotes: 1

Related Questions