Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 468
Gildas.Tambo Avatar asked Sep 16 '25 16:09

Gildas.Tambo


1 Answers

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);
like image 87
James Montagne Avatar answered Sep 18 '25 06:09

James Montagne