Gildas.Tambo
Gildas.Tambo

Reputation: 22653

cloneNode vs innerHTML

I am trying to clone a template in a header using the Node.cloneNode() without success. Here is my markup

var header = document.querySelector("header"),
$templateHeader = document.querySelector("[data-template=header]");

header.innerHTML = $templateHeader.innerHTML;
<header></header>

<!--templates-->
<template data-template=header>
  <div class=container>
    <menu class=row>
      <li><a>Home</a></li>
      <li><a>items</a></li>
      <li><a>Reseller</a></li>
      <li><a>Shop</a></li>
    </menu>
  </div>
</template>

This works just fine

header.innerHTML = $templateHeader.innerHTML;

while this will not work

var header = document.querySelector("header"),
$templateHeader = document.querySelector("[data-template=header]");

header.innerHTML = $templateHeader.cloneNode(true);
<header></header>

<!--templates-->
<template data-template=header>
  <div class=container>
    <menu class=row>
      <li><a>Home</a></li>
      <li><a>items</a></li>
      <li><a>Reseller</a></li>
      <li><a>Shop</a></li>
    </menu>
  </div>
</template>

even this

var header = document.querySelector("header"),
$templateHeader = document.querySelector("[data-template=header]");

header.appendChild($templateHeader.cloneNode(true));
<header></header>

<!--templates-->
<template data-template=header>
  <div class=container>
    <menu class=row>
      <li><a>Home</a></li>
      <li><a>items</a></li>
      <li><a>Reseller</a></li>
      <li><a>Shop</a></li>
    </menu>
  </div>
</template>

when i console.log $templateHeader.cloneNode(true) this is what i get

enter image description here

Can anyone help me understanding what i am doing wrong here?

Note: i don't want to use jquery

regards, Tambo

Upvotes: 3

Views: 1739

Answers (1)

James Montagne
James Montagne

Reputation: 78710

You have cloned the entire template and are trying to append the template to your header. You don't want to do that, you want to append the content of the template.

var header = document.querySelector("header"),
$templateHeader = document.querySelector("[data-template=header]");

header.appendChild($templateHeader.content.cloneNode(true));
<header></header>

<!--templates-->
<template data-template=header>
  <div class=container>
    <menu class=row>
      <li><a>Home</a></li>
      <li><a>items</a></li>
      <li><a>Reseller</a></li>
      <li><a>Shop</a></li>
    </menu>
  </div>
</template>

That said, in a number of samples I found online, I found importNode used instead of cloneNode:

var clone = document.importNode(t.content, true);

Upvotes: 4

Related Questions